Find and open file in a connected USB - java

So the logic is:
User connects a USB to Android device.
User press "Find Update" button.
The App connects to the USB and finds in the main folder any .apk file.
The App opens the .apk file found in the USB.
The .apk runs and update the current App.
What I have so far:
findUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean foundUsb = false;
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
deviceList = usbManager.getDeviceList();
deviceIterator = deviceList.values().iterator();
Log.d("UPDATER", "Pressed");
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
Log.d("UPDATER", "Device Attached: " + device.getManufacturerName());
if (!Objects.equals(device.getManufacturerName(), gv.getManufacturerIDPlaca())) {
Log.d("UPDATER", device.getManufacturerName());
foundUsb = true;
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(SetupActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
if (!usbManager.hasPermission(device)) {
Log.d("UPDATER", "No access");
usbManager.requestPermission(device, mPermissionIntent);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
}
Log.d("UPDATER", "Has access");
usbDevice = device;
usbInterface = usbDevice.getInterface(0);
usbEndpoint = usbInterface.getEndpoint(0);
usbDeviceConnection = usbManager.openDevice(usbDevice);
packetSize = usbEndpoint.getMaxPacketSize();
new Thread(new Runnable() {
public void run() {
final byte[] buffer = new byte[packetSize];
usbDeviceConnection.claimInterface(usbInterface, forceClaim);
usbDeviceConnection.bulkTransfer(usbEndpoint, buffer, packetSize, TIMEOUT);
Log.d("UPDATER", String.valueOf(buffer));
}
}).start();
}
}
if (!foundUsb) {
Toast.makeText(context, "No USB detected", Toast.LENGTH_SHORT).show();
}
}
});
What this code returns me in console is a buffer (of bytes) converted to a String.
I'm wondering how could I find a file let's say app.apk and open it to actually update the current app (where the button is pressed from).

I finally came up with a solution:
findUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean foundUsb = false;
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
deviceList = usbManager.getDeviceList();
deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
Log.d("UPDATER", "Device Attached: " + device.getManufacturerName());
if (!Objects.equals(device.getManufacturerName(), gv.getManufacturerIDPlaca())) {
foundUsb = true;
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(SetupActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
if (!usbManager.hasPermission(device)) {
usbManager.requestPermission(device, mPermissionIntent);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
}
try {
File file = new File("/storage/usbhost/update-binary.apk");
if (file.exists()) {
Intent newIntent = new Intent(Intent.ACTION_VIEW);
newIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
else {
Toast.makeText(getApplicationContext(), R.string.UPDATE_APK_NO_ENCONTRADA, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
if (!foundUsb) {
Toast.makeText(context, R.string.USB_NO_CONECTADO, Toast.LENGTH_SHORT).show();
}
}
});

Related

Android not connecting to bluetooth controller

private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
}
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
if (device.getName() != null) {
if (device.getName().equals("HMSoft")){
Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT).show();
try {
blueSocket = device.createRfcommSocketToServiceRecord(applicationUUID);
Toast.makeText(MainActivity.this, "A", Toast.LENGTH_SHORT).show();
blueAdapter.cancelDiscovery();
Toast.makeText(MainActivity.this, "B", Toast.LENGTH_SHORT).show();
blueSocket.connect();
Toast.makeText(MainActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
} catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
bluetoothDevices.add(device);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
System.out.println(deviceName);
System.out.println(deviceHardwareAddress);
}
}
When you click on the button that activates the execution of this code, the button itself freezes.
Errors:
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
I/System.out: read failed, socket might closed or timeout, read ret: -1

Send data from my App android to my Raspberry PI 3

Hi i am actually working on app to send command line on the terminal of my Raspberry PI 3.
I wouldlike when i press the button save for example to send the command "ls" to my RPI3.
Acutally, I've got some problem with my object BluetoothconnectionService.
I think I can't send data because my object is not declared on my activity "Accueil" ? `
BluetoothConnectionService.java :
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
private ConnectedThread mConnectedThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
Context mContext;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private BluetoothSocket socket = null;
private InputStream mmInStream;
private String device;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
int error=2;
int i;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
error=1;
}catch (NullPointerException e){
e.printStackTrace();
error=0;
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
final String strReceived = new String(buffer,0,bytes);
final String strByteCnt = String.valueOf(bytes) + "bytes received. \n";
// Send the obtained bytes to the UI activity
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
MainActivity.java :`
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
// variables
private static final String TAG = "MainActivity";
private Uri[] mFileUris = new Uri[10];
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
// Bluetooth object
BluetoothAdapter mBluetoothAdapter;
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// variables button
Button btnStartConnection;
Button scan;
// Image button
ImageButton btnONOFF;
// Variables affichages
StringBuilder messages;
ListView lvNewDevices;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Constructor
mBTDevices = new ArrayList<>();
messages = new StringBuilder();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
// list findViewbyID
btnONOFF = (ImageButton) findViewById(R.id.bluetooth_on_off);
scan = (Button) findViewById(R.id.scan);
btnStartConnection = (Button) findViewById(R.id.Connect);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
// divers
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
// ON/OFF BLUETOOTH
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableDisableBT();
}
});
// SCAN
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDiscover();
btnEnableDisable_Discoverable();
}
});
// CONNECTION
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
}
// 4 BroadcastReceiver
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
//inside BroadcastReceiver4
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
//create method for starting connection
public void startConnection(){
startBTConnection(mBTDevice,MY_UUID_INSECURE);
goToAcceuil();
}
public void startBTConnection(BluetoothDevice device, UUID uuid){
Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
mBluetoothConnection.startClient(device,uuid);
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover() {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
}
}
public void goToAcceuil (){
Intent intent = new Intent (this,Accueil.class);
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("mBTDevice",mBTDevice);
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
startActivity(intent);
}
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
}
Accueil.java :
public class Accueil extends AppCompatActivity {
// Bluetooth
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// String
String name_device1;
String adress_device1;
String freq_value1;
String item_spin1;
String item_spin;
// Image Button
ImageButton btn_back;
ImageButton btn_accueil;
ImageButton btn_voice;
ImageButton btn_scan;
ImageButton btn_settings;
// Button
Button btn_send_freq;
// Textview
TextView name_device;
TextView adress_device;
// Edit Text
EditText freq_value;
// List
ArrayAdapter<String> adapter;
List<String> list;
// Spinner
Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
// Variables from other activity
name_device1= getIntent().getStringExtra("DEVICE_NAME");
adress_device1=getIntent().getStringExtra("DEVICE_ADRESS");
mBTDevice=getIntent().getExtras().getParcelable("mBTDevice");
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
freq_value1=getIntent().getStringExtra("VALUE_FREQ");
item_spin1=getIntent().getStringExtra("VALUE_SPIN");
// findView by ID
name_device= (TextView) findViewById(R.id.name_device2);
adress_device= (TextView) findViewById(R.id.adress_device2);
btn_back = (ImageButton) findViewById(R.id.back1);
btn_accueil = (ImageButton) findViewById(R.id.accueil1);
btn_voice = (ImageButton) findViewById(R.id.voice1);
btn_scan = (ImageButton) findViewById(R.id.scan1);
btn_settings= (ImageButton) findViewById(R.id.settings1);
btn_send_freq = (Button) findViewById(R.id.send_freq1);
freq_value = (EditText) findViewById(R.id.value_freq1);
spinner1=(Spinner) findViewById(R.id.spinner_freq);
// SetText
name_device.setText(name_device1);
adress_device.setText(adress_device1);
freq_value.setText(freq_value1);
// Spinner
list=new ArrayList<String>();
list.add("MHz");
list.add("GHz");
adapter= new ArrayAdapter<String>(this,R.layout.spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
btn_send_freq.setOnClickListener(new View.OnClickListener() { // Bouton Save
#Override
public void onClick(View view) {
send_freq();
}
});
btn_back.setOnClickListener(new View.OnClickListener() { // Bouton RETOUR
#Override
public void onClick(View view) {
gotoBack();
}
});
btn_accueil.setOnClickListener(new View.OnClickListener() { // Bouton ACCUEIL
#Override
public void onClick(View view) {
gotoAccueil();
}
});
btn_voice.setOnClickListener(new View.OnClickListener() { // Bouton VOICE
#Override
public void onClick(View view) {
gotoVoice();
}
});
btn_scan.setOnClickListener(new View.OnClickListener() { // Bouton SCAN
#Override
public void onClick(View view) {
gotoScan();
}
});
btn_settings.setOnClickListener(new View.OnClickListener() { // Bouton SETTINGS
#Override
public void onClick(View view) {
gotoSettings();
}
});
}
// Fonction
public void send_freq()
{
byte[] bytesToSend="sudo rm azertyy".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
// Fonctions onglets
public void gotoBack() // Onglet PRECEDENT
{
Intent intent = new Intent (this,MainActivity.class);
startActivity(intent);
}
public void gotoAccueil() // Onglet ACCUEIL
{
Intent intent = new Intent (this,Accueil.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoVoice() // Onglet VOICE
{
Intent intent = new Intent (this,voice.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoScan() // Onglet SCAN
{
Intent intent = new Intent (this,Scan.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoSettings() // Onglet SETTINGS
{
Intent intent = new Intent (this,connection.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
}
With this function, I wouldlike to send "ls" on the terminal of my RPI3 :`
public void send_freq()
{
byte[] bytesToSend="ls".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
But I don't understand, I have some error like that :enter image description here
I tried to resolve that with Parcelable, but no sucess... enter image description here
So my code does not work. My app crash all time...
Thanks for any help !
From my understanding you have a button inside your MainActivity.java that opens another Activity (Accueil.java) via an Intent. And in doing so, you are sending an Intent with extras to transfer data between them.
An Intent can only take an object as an extra if it implements the Parcelable interface.
Here you attempted to add BluetoothConnectionService that does not implement Parcelable.
You commented it out because it was giving you the error you showed in the screenshot.
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
Which means inside of Accueil.java your mBluetoothConnection will be null causing your app to crash.
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
Solutions to this problem would be to either
Find a way to make BluetoothConnectionService implement Parcelable
If possible, re-instantiate BluetoothConnectionService.

Getting an android app to detect NFC tags

I have created an android app for reading NFC tags. It can detect if an NFC is around, however it can't read the contents on it nor can I write anything on it. I also have problem with my code on line 79 of the read_write_successful class. I made use of the "createNdefMessage" method that was declared on line 190.
Below is my code:
read_write_successful class
public class read_write_successful extends AppCompatActivity {
NfcAdapter nfcAdapter;
ToggleButton tglReadWrite;
TextView txtTagContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mattie_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
tglReadWrite = (ToggleButton)findViewById(R.id.tglReadWrite);
txtTagContent = (TextView)findViewById(R.id.txtTagContent);
}
#Override
protected void onResume() {
super.onResume();
enableForegroundDispatchSystem();
}
#Override
protected void onPause() {
super.onPause();
disableForegroundDispatchSystem();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(this, "NFC intent received!", Toast.LENGTH_LONG).show();
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)){
if (tglReadWrite.isChecked()){
Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (parcelables != null && parcelables.length > 0){
readTextFromMessage((NdefMessage)parcelables[0]);
}
else {
Toast.makeText(this, "No NDEF messages found!", Toast.LENGTH_SHORT).show();
}
}
else {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage ndefMessage = createNdefMessage(txtTagContent.getText() + "");
byte[] payload = "my string".getBytes();
NdefRecord ndefRecord = NdefRecord.createExternal("nfctutorials", "externaltype", payload);
ndefMessage = new NdefMessage(new NdefRecord[]{ ndefRecord });
writeNdefMessage(tag, ndefMessage);
}
}
}
private void readTextFromMessage(NdefMessage ndefMessage) {
NdefRecord[] ndefRecords = ndefMessage.getRecords();
if (ndefRecords != null && ndefRecords.length > 0){
NdefRecord ndefRecord = ndefRecords[0];
String tagContent = getTextFromNdefRecord(ndefRecord);
txtTagContent.setText(tagContent);
}
else {
Toast.makeText(this, "No NDEF records found!", Toast.LENGTH_SHORT).show();
}
}
private void enableForegroundDispatchSystem(){
Intent intent = new Intent(this, read_write_successful.class).addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
private void disableForegroundDispatchSystem(){
nfcAdapter.disableForegroundDispatch(this);
}
private void formatTag(Tag tag, NdefMessage ndefMessage){
try{
NdefFormatable ndefFormatable = NdefFormatable.get(tag);
if (ndefFormatable == null){
Toast.makeText(this, "Tag is not ndef formatable", Toast.LENGTH_SHORT).show();
return;
}
ndefFormatable.connect();
ndefFormatable.format(ndefMessage);
ndefFormatable.close();
Toast.makeText(this, "Tag written!", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Log.e("formatTag",e.getMessage());
}
}
private void writeNdefMessage(Tag tag, NdefMessage ndefMessage){
try{
if (tag == null){
Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
return;
}
Ndef ndef = Ndef.get(tag);
if (ndef == null){
//format tag with the ndef format and writes the message.
formatTag(tag, ndefMessage);
}
else {
ndef.connect();
if (!ndef.isWritable()){
Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();
ndef.close();
return;
}
ndef.writeNdefMessage(ndefMessage);
ndef.close();
Toast.makeText(this, "Tag written!", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Log.e("writeNdefMessage",e.getMessage());
}
}
private NdefRecord createTextRecord(String content){
try {
byte[] language;
language = Locale.getDefault().getLanguage().getBytes("UTF-8");
final byte[] text = content.getBytes("UTF-8");
final int languageSize = language.length;
final int textLength = text.length;
final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);
payload.write((byte) (languageSize & 0x1F));
payload.write(language, 0, languageSize);
payload.write(text, 0, textLength);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
}
catch (UnsupportedEncodingException e){
Log.e("createNdefMessage",e.getMessage());
}
return null;
}
private NdefMessage createNdefMessage(String content){
NdefRecord ndefRecord = createTextRecord(content);
return new NdefMessage(new NdefRecord[]{ndefRecord});
}
public void tglReadWriteOnClick(View v){
txtTagContent.setText("");
}
public String getTextFromNdefRecord(NdefRecord ndefRecord){
String tagContent = null;
try {
byte[] payload = ndefRecord.getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
int languageSize = payload[0] & 51;
tagContent = new String(payload, languageSize + 1,
payload.length - languageSize - 1, textEncoding);
}
catch (UnsupportedEncodingException e){
Log.e("getTextFromNdefRecord", e.getMessage(), e);
}
return tagContent;
}
}
MainActivity class
public class MainActivity extends AppCompatActivity {
private KeyStore keyStore;
// Variable used for storing the key in the Android Keystore container
private static final String KEY_NAME = "WERTY";
private Cipher cipher;
TextView mattie;
Button Login;
Button SignUp;
Button NextButton;
Button WriteButton;
NfcAdapter nfcAdapter;
ToggleButton tglReadWrite;
EditText txtTagContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Login = (Button) findViewById(R.id.btn_logIn);
SignUp = (Button)findViewById(R.id.btn_signUp);
NextButton = (Button)findViewById(R.id.btn_next);
WriteButton = (Button)findViewById(R.id.btn_write);
mattie = (TextView)findViewById(R.id.txtMatma);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/Praetoria D.otf");
mattie.setTypeface(myCustomFont);
findViewById(R.id.btn_play_again).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// We normally won't show the welcome slider again in real app
// but this is for testing
PrefManager prefManager = new PrefManager(getApplicationContext());
// make first time launch TRUE
prefManager.setFirstTimeLaunch(true);
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish();
}
});
// Initializing both Android Keyguard Manager and Fingerprint Manager
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
// Checks whether fingerprint permission is set on manifest
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
// Check whether the device has a Fingerprint sensor.
if (!fingerprintManager.isHardwareDetected()) {
Toast.makeText(this, "Your Device does not have a Fingerprint Sensor", Toast.LENGTH_SHORT).show();
}
else {
// Checks whether fingerprint permission is set on manifest
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Fingerprint authentication permission not enabled", Toast.LENGTH_SHORT).show();
} else {
// Check whether at least one fingerprint is registered
if (!fingerprintManager.hasEnrolledFingerprints()) {
Toast.makeText(this, "Register at least one fingerprint in Settings", Toast.LENGTH_SHORT).show();
} else {
// Checks whether lock screen security is enabled or not
if (!keyguardManager.isKeyguardSecure()) {
Toast.makeText(this, "Lock Screen security not enabled in Settings", Toast.LENGTH_SHORT).show();
} else {
genKey();
}
if (cipherInit()) {
FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this);
Register assistance = new Register(this);
helper.startAuthentication(fingerprintManager, cryptoObject);
assistance.startAuthentication(fingerprintManager, cryptoObject);
}
}
}
}
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
tglReadWrite = (ToggleButton)findViewById(R.id.tglReadWrite);
txtTagContent = (EditText) findViewById(R.id.txtTagContent);
if (nfcAdapter!=null && nfcAdapter.isEnabled()){
Toast.makeText(this, "NFC available!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "NFC not available! Kindly switch it on in your phone's settings.", Toast.LENGTH_SHORT).show();
finish();
}
}
#TargetApi(Build.VERSION_CODES.M)
private void genKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
}
catch (Exception e) {
e.printStackTrace();
}
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new RuntimeException("Failed to get KeyGenerator instance", e);
}
try {
keyStore.load(null);
keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()
);
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
throw new RuntimeException(e);
}
}
#TargetApi(Build.VERSION_CODES.M)
private boolean cipherInit() {
try {
cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES+ "/" +KeyProperties.BLOCK_MODE_CBC+ "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new RuntimeException("Failed to get Cipher", e);
}
try {
keyStore.load(null);
SecretKey key = (SecretKey)keyStore.getKey(KEY_NAME, null);
cipher.init(Cipher.ENCRYPT_MODE, key);
return true;
} catch (KeyPermanentlyInvalidatedException e) {
return false;
} catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to init Cipher", e);
}
}
public void signUpBtn(View v){
Intent iv = new Intent(this, CardNumberSignUpActivity.class);
startActivity(iv);
}
public void loginBtn(View v){
Intent i = new Intent(this,LoginSuccessfulActivity.class);
startActivity(i);
}
public void nextBtn(View v){
Intent ii = new Intent(this, register_security_successful.class);
startActivity(ii);
}
public void writeBtn(View v){
Intent iii = new Intent(this, read_write_successful.class );
startActivity(iii);
}
}
read_write_successful layout [Relative Layout]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ToggleButton
android:text="ToggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tglReadWrite"
android:textOn="#string/txtOn"
android:textOff="#string/txtOff"
android:checked="true"
android:onClick="tglReadWriteOnClick"/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtTagContent"
android:layout_below="#+id/tglReadWrite"
android:inputType="text" />
</RelativeLayout>

How to send data via USB communication from Android device?

I would like to send data (string) via USB communication from my Android application to a device. I am beginner in Android development, so I followed this tutorial: http://developer.android.com/guide/topics/connectivity/usb/host.html
Somehow the part Communicating with a device doesn't work, doesn't send any text to the device. I tried to send data also with
connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);
or with
ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);
request.initialize(connection, epOut);
request.queue(buffer, bytes.length);
but nothing worked.
I don't really understand, how could I send a short text for example "#V" to the device from my android app.
Could you please help me find the problem in my code? Thanks in advance.
Here is my MainActivity class:
public class MainActivity extends AppCompatActivity {
UsbDevice device;
Button bShow;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
Boolean isDevice = true;
TextView tvTest;
String sendText = "#V";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
int controlTransferResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTest = (TextView) findViewById(R.id.textView);
showData();
}
public void showData(){
bShow= (Button)findViewById(R.id.button);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Log.e("MainActivity", "DeviceList:" + deviceList.toString());
if(deviceList.toString().equals("{}")){
Toast.makeText(MainActivity.this,"No USB device found!", Toast.LENGTH_SHORT).show();
return;
}else{
tvTest.setText(deviceList.toString());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
//while(deviceIterator.hasNext()) {
device = deviceIterator.next();
//}
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mUsbManager.requestPermission(device, mPermissionIntent);
bShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, device.getDeviceName() + "\n"
+ device.getManufacturerName() + "\n"
+ device.getProductName() + "\n"
+ device.getVendorId() + "\n"
+ device.getDeviceId() + "\n"
+ "i=" + controlTransferResult, Toast.LENGTH_SHORT).show();
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
UsbInterface intf = device.getInterface(0);
UsbEndpoint epOut = null;
UsbEndpoint epIn = null;
// look for our bulk endpoints
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
//Log.d(TAG, "EP " + i + ": " + ep.getType());
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
epOut = ep;
} else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
epIn = ep;
}
}
}
if (epOut == null || epIn == null) {
throw new IllegalArgumentException("Not all endpoints found.");
}
//UsbEndpoint endpoint = intf.getEndpoint(1);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = sendText.getBytes();
controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);//baudrate 9600
//int res = connection.bulkTransfer(epOut, bytes, bytes.length, TIMEOUT); //do in another thread
ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);
request.initialize(connection, epOut);
request.queue(buffer, bytes.length);
}
}
else {
Log.d("MyActivity", "permission denied for device " + device);
}
}
}
}
};
}
You need to prepare drivers for your Android device first, for example, if your device is using CP210X chipset for USB support you should follow these steps: https://www.silabs.com/documents/public/application-notes/AN809.pdf

Gmail crash when trying to send mail with and attachement

Trying to make audio record and then send it with GMAIL app, but it crushes and tells about null pointer exception and blah-blah-blah see the picture below.
I'm trying to make a record within 5 seconds, then stop the timer and send the email message.
Also my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recordMemo.3gp";
eDB = new dbConfig(this);
sqlDB = eDB.getWritableDatabase();
smsPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
smsText = smsPreferences.getString("smsTXT", "I'll call you later");
Log.d("TEXT", smsText);
gpsManager = new GPSManager();
gpsManager.startListening(getApplicationContext());
gpsManager.setGPSCallback((GPSCallback) this);
StateListener phoneStateListener = new StateListener();
telephonymanager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
telephonymanager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
//gpsInfo = (TextView) findViewById(R.id.gps_info);
//gpsInfo.setText(getString(R.string.gpsSPEED));
//
}
CountDownTimer start = new CountDownTimer(5000, 1000) {
#Override
public void onTick(long l) {
//Toast.makeText(getApplicationContext(), "Recording!!!",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
Log.d("STOP", "STOP");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
}
catch (RuntimeException e) {
e.printStackTrace();
}
if (action.equals("1")) {
//Log.d("OUTPUT", outputFile);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("application/octet-stream");
share.putExtra(Intent.EXTRA_SUBJECT, "My Memo");
share.putExtra(Intent.EXTRA_TEXT, "Sending my memo");
share.putExtra(Intent.EXTRA_EMAIL,
new String[] { myEmail });
share.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://" + outputFile));
MainActivity.this.startActivity(share);
}
}
}.start();

Categories