Android screen freezes while sending data to usb device - android

I have following problem - I need to send data to my usb device and read tag of the device. First I need to turn on device - that's what table pal does. Next, when response from device equals DAAD0674016F6B26 I need to start scan - table readId. After that depends if response is DAAD046F62ADA900 - that means that in 3 sec device didn't found tag to scan and device turned off. My task is to send again command to turn it on ... and again, and again and so on (I know it's quite expensive - command every 3 sec - it wasn't my idea). But , when the response is different than DAAD046F62ADA900 - that's my tag :)To sum up - if response is DAAD046F62ADA900 I need to send command to scan again I try to do it with while loop :
while(shouldReceive) {
sendCommand
}
but the screen freezes so I tried to do it in thread , and right now it looks like this :
final Thread receive= new Thread(new Runnable() {
public UsbDevice device;
#Override
public void run() {
usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getActivity().registerReceiver(usbReceiver, filter);
shouldReceaive = true;
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
final UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 1659 && device.getProductId() == 8963) {
this.device = device;
usbManager.requestPermission(device, mPermissionIntent);
break;
}
}
final UsbConnector.CallbackListener listener = new UsbConnector.CallbackListener() {
#Override
public void onStatusChanged(UsbConnector.Status newStatus) {
Toast.makeText(getContext(), "Status" + newStatus, Toast.LENGTH_SHORT).show();
}
#Override
public void onScanCompleted(String result) {
Toast.makeText(getContext(), "Result" + result, Toast.LENGTH_SHORT).show();
}
};
shouldReceaive = true;
UsbConnector connector = new UsbConnector(getContext(), device, listener);
connector.run();
connector.send(pal);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] received = connector.receive(36);
if (received == null) {
Toast.makeText(getContext(), "Błąd inicjalizacji skanera", Toast.LENGTH_SHORT).show();
}
if (received != null) {
String response = null;
long longValue = ByteBuffer.wrap(received).getLong();
response = Long.toHexString(longValue).toUpperCase();
Toast.makeText(getContext(), "RESPONSE: " + response, Toast.LENGTH_SHORT).show();
if (response.contentEquals("DAAD0674016F6B26")) {
Toast.makeText(getContext(), "Rozpoczynam skanowanie ...", Toast.LENGTH_SHORT).show();
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] receivedTag = connector.receive(36);
if (receivedTag != null) {
String tag = null;
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
tag = Long.toHexString(tagValue).toUpperCase();
while (tag.contentEquals("DAAD046F62ADA900")) {
Toast.makeText(getContext(), "PING, SKANUJE DALEJ!", Toast.LENGTH_SHORT).show();
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String tag2 = null;
long tagValue2 = ByteBuffer.wrap(receivedTag).getLong();
tag2 = Long.toHexString(tagValue2).toUpperCase();
Toast.makeText(getContext(), "ZESKANOWANY TAG!: " + tag2, Toast.LENGTH_SHORT).show();
for (Car cary : carList) {
if (tag2.contentEquals(cary.getmNumber())) {
Log.e(TAG, "setCars: JEST");
} else {
Log.e(TAG, "setCars: NIE MA");
}
}
}
} else {
Toast.makeText(getContext(), "Błąd przy inicjalziacji skanera", Toast.LENGTH_SHORT).show();
}
}
}
});
mScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
receive.run();
}
});
but problem still exists. Screen freezes and user can do nothing. Any idea how to solve this problem ?

When you invoke run() method, it's executed on the calling thread (in your case on UI thread).
#Override
public void onClick(View v) {
receive.run();
}
Try this:
#Override
public void onClick(View v) {
receive.start();
}

Related

my Bluetooth cannot connect to the device

i am trying to use my android phone to connect to the pc or hc01 but know the code that i write cannot connect to the phone now so anyone can help me out
and the UUID what should i use or have anyone have some demon for me to try out
thanks
i don't why i click and it always connect fail and the logcat will get
com.example.lord1.myapplication123123 W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
this is my code:
private void discover(View view){
// Check if the device is already discovering
if(mBTAdapter.isDiscovering()){
mBTAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(mBTAdapter.isEnabled()) {
mBTArrayAdapter.clear(); // clear items
mBTAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
}
}
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mBTArrayAdapter.notifyDataSetChanged();
}
}
};
private void listPairedDevices(View view){
mPairedDevices = mBTAdapter.getBondedDevices();
if(mBTAdapter.isEnabled()) {
// put it's one to the adapter
for (BluetoothDevice device : mPairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if(!mBTAdapter.isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
// Spawn a new thread to avoid blocking the GUI one
new Thread()
{
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if(fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};

Retain Bluetooth Connection till the app is Closed

I made an app which connects to bluetooth and sends and receive data in an activity. Now I have updates in the app and has to create another activities which connects to the same bluetooth device and transfer data. So I am planning to connect to bluetooth device in my second activity which has some buttons which calls for another activities. I need to retain the bluetooth connection I made in the second activity throughout the activities that are called from the second activity using buttons till the user press back button from second activity (exiting second activity). Please explain how I should change my code to make this happen. This is my current code which is used for single activity bluetooth connection.
public class ViewBoardStatus extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_board_status);
mOutStringBuffer = new StringBuffer("");
IntentFilter filter = new IntentFilter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
List<String> paireddevicesarray = new ArrayList<>();
int iNoOfPariedDev = pairedDevices.size();
int iDeviceCntr = 0;
DevAddressString = new String[iNoOfPariedDev][2];
for (BluetoothDevice device : pairedDevices)
{
DevAddressString[iDeviceCntr][0] = device.getAddress();
DevAddressString[iDeviceCntr][1] = device.getName();
iDeviceCntr++;
if (iDeviceCntr > iNoOfPariedDev)
break;
}
ArrayList<String> aList = new ArrayList<String>();
aList.add("Select Device");
for (int i = 0; i < iDeviceCntr; i++)
{
aList.add(DevAddressString[i][1]);
}
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, aList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_paireddevices.setAdapter(dataAdapter);
sp_paireddevices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
Log.e(TAG, "Executing On ITEM SELECTED");
int iLoc = sp_paireddevices.getSelectedItemPosition();
if (iLoc != 0)
{
Toast.makeText(getApplicationContext(), " Connecting to hardware please wait..", Toast.LENGTH_SHORT).show();
iBTDevSelcted = 1;
Log.e(TAG, "Toast message of Connecting");
address = DevAddressString[iLoc - 1][0];
Log.e(TAG, "Calling OnResume Function");
onResume();
}
else
{
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
lvParaHeader.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaValue.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaValue.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(touchSource == null)
touchSource = v;
if(v == touchSource)
{
lvParaHeader.dispatchTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP)
{
clickSource = v;
touchSource = null;
}
}
return false;
}
});
lvParaHeader.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaValue.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(parent == clickSource) {
// Do something with the ListView was clicked
}
}
});
lvParaHeader.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaValue.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
lvParaValue.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(view == clickSource)
lvParaHeader.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
sp_datatype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.e(l,"Starting ON Item Selected");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
bt_Refresh.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(l,"Refresh Button OnClick");
if (sp_paireddevices.getSelectedItemPosition()>0)
{
if (sp_datatype.getSelectedItemPosition() == 0) {
Toast.makeText(getApplicationContext(), " Select a Parameter to Refresh ", Toast.LENGTH_SHORT).show();
}
if (sp_datatype.getSelectedItemPosition() == 1) {
sGetRequest = sGetElectricalPara;
sendMessage(sGetRequest);
Log.e(l, "Send Message Called");
}
if (sp_datatype.getSelectedItemPosition() == 2) {
sGetRequest = sGetGprsPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 3) {
sGetRequest = sGetSystemPara;
sendMessage(sGetRequest);
}
if (sp_datatype.getSelectedItemPosition() == 4) {
sGetRequest = sGetRS485Para;
sendMessage(sGetRequest);
}
Log.e(l, "Send Message Called");
}
else
Toast.makeText(getApplicationContext(), " Connect to a Device and Refresh ", Toast.LENGTH_SHORT).show();
}
});
h = new Handler()
{
public void handleMessage(android.os.Message msg)
{
Log.e(l, "Starting Handler");
int strlen;
switch (msg.what)
{
case RECIEVE_MESSAGE:
Log.d(l, "data received = " );
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
String strMsg = new String();
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("#");
if (endOfLineIndex > 0)
{ // if end-of-line,
sJsonData = sb.substring(1, endOfLineIndex); // extract string
sb.delete(0, sb.length());
// and clear
try
{
Log.e(l, "Starting Try of Handler");
Log.e(l, "Data Received: "+sJsonData);
strlen = sJsonData.length();
Log.e(l, "String Length Obtained");
JSONObject mainobject = new JSONObject(sJsonData);
Log.e(l, "main object created");
sDataType = mainobject.getString("DATA_TYPE");
Log.e(l, "Data Type Obtained");
//tv_jsonlength.setText(String.valueOf(strlen));
//tv_JsonPara.setText(TempHeader);
iSelectedParaPostion=sp_datatype.getSelectedItemPosition();
if(sDataType.trim().equalsIgnoreCase("PARA"))
{
if(iSelectedParaPostion==1)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparseelectricalpara();
}
}
if(sDataType.trim().equalsIgnoreCase("GPRS"))
{
if(iSelectedParaPostion==2)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//tv_jsonstring.setText(sCurrentJsonData);
jsonparsegprsdata();
}
}
if(sDataType.trim().equalsIgnoreCase("SYSTEM"))
{
if(iSelectedParaPostion==3)
{
sCurrentJsonData = sJsonData;
Log.e(l, "sCurrentJsonData set to sJsonData");
//
// tv_jsonstring.setText(sCurrentJsonData);
jsonparseSystem();
}
}
}
catch (Exception e)
{
Log.e(l, "CATCH OF HANDLER");
}
}
break;
}
}
};
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}//oncreate
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(mBluetoothAdapter==null) {
// Log.d(TAG, "error, bluetooth not supported");
} else {
if (mBluetoothAdapter.isEnabled()) {
// Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
tvconnectionstatus.setText("");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
Log.e(TAG, "Bluetooth Socket Creation TRY EXECUTED");
return (BluetoothSocket) m.invoke(device, MY_UUID);
}
catch (Exception e2)
{
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Bluetooth Socket Creation CATCH EXECUTED");
}
}
Log.e(TAG, "Exiting Socket Creation Method");
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void onResume()
{
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.e(TAG, "Starting OnResume Method");
if (iBTDevSelcted == 0) {
Toast.makeText(getApplicationContext(), " Please select Bluetooth Device", Toast.LENGTH_SHORT).show();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e(TAG, "Obtaining REMOTE DEVICE address");
try {
btSocket = createBluetoothSocket(device);
Log.e(TAG, "BT SOCKET Created");
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
mBluetoothAdapter.cancelDiscovery();
Log.e(TAG, "BT Discovery CANCELLED");
try
{
Log.e(TAG, "TRY STATEMENT OF BT CONNECTION CREATION");
btSocket.connect();
String connectedto = "Connected to: " + sp_paireddevices.getSelectedItem().toString();
tvconnectionstatus.setText(connectedto);
}
catch (IOException e)
{
Log.e(TAG, "CATCH STATEMENT OF BLUETOOTH CONNECTION CREATION");
try {
btSocket.close();
Log.e(TAG, "Bluetooth Socket Closed");
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.e(TAG, "Unable to Close bluetooth connection");
}
}
// Create a data stream so we can talk to server.
// Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
Log.e(TAG, "Connection Thread Created");
mConnectedThread.start();
Log.e(TAG, "Connection Thread Started");
}
#Override
public void onPause()
{
super.onPause();
// Log.d(TAG, "...In onPause()...");
if(iBTDevSelcted==1) {
try {
btSocket.close();
tvconnectionstatus.setText("");
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
}
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try
{
Log.e(TAG, "Trying to get Temp Input/Output Stream");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.e(TAG, "Input/Output Stream Obtained");
}
catch (IOException e)
{
Log.e(TAG, "I/O Stream CATCH STATEMENT");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
Log.e(TAG, "Starting RUN Method");
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 {
Log.e(TAG, "TRY of RUN Method Started");
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
Log.e(l,"Run Executed");
Log.e(TAG, "TRY of RUN Method Completed");
} catch (IOException e)
{
Log.e(TAG, "CATCH of RUN Method");
break;
}
}
}
public void write(String s) throws IOException
{
mmOutStream.write(s.getBytes());
tvconnectionstatus.setText(s);
sGetRequest=sReset;
}
}//connectthread
private void sendMessage(String message)
{
ConnectedThread ct;
Log.e(l,"Connected Thread Object Created");
ct = mConnectedThread;
try {
ct.write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}//class

Android : AsyncTaks blocks my interface

I got problem with my asyncTask. I have my custom USB Scanner. I want to turn it on and off with ToggleButton. Scanning works fine but asynctask completly blocks user interface. I can't do nothing. Maybe you know what can I do to make it works better ?
Here's toggleButton :
mScanLayout.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
task.execute();
if(!isChecked)
task.cancel(true);
}
});
Here is asynctask :
public class scanAsyncTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
while(!isCancelled()) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity,this);
adapter.startScanning();
}
});
}
return null;
}
}
And this is scanning method from adapter :
public void startScanning(){
final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getContext().registerReceiver(usbReceiver, filter);
UsbManager usbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = null;
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
if (device.getVendorId() == 1659 && device.getProductId() == 8963) {
this.device = device;
usbManager.requestPermission(device, mPermissionIntent);
break;
}
}
final UsbDevice finalDevice = device;
final UsbDevice finalDevice1 = device;
UsbConnector.CallbackListener listener = new UsbConnector.CallbackListener() {
#Override
public void onStatusChanged(UsbConnector.Status newStatus) {
Toast.makeText(getContext(), "status: " + newStatus, Toast.LENGTH_SHORT).show();
}
#Override
public void onScanCompleted(String result) {
Toast.makeText(getContext(), "result: " + result, Toast.LENGTH_SHORT).show();
}
};
UsbConnector connector = new UsbConnector(getContext(), finalDevice1,listener);
connector.run();
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(finalDevice);
UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(finalDevice, usbDeviceConnection);
serial.open();
serial.setBaudRate(57600);
if (finalDevice1 != null) {
connector.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
connector.send(pal);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] received = connector.receive(36);
if (received == null) {
Toast.makeText(getContext(), "BĹ‚Ä…d inicjalizacji skanera", Toast.LENGTH_SHORT).show();
}
if (received != null) {
String response = null;
long longValue = ByteBuffer.wrap(received).getLong();
response = Long.toHexString(longValue).toUpperCase();
if (response.contains("DAAD0674016F6B26")) {
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] receivedTag = connector.receive(36);
if (receivedTag != null) {
String tag = null;
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
tag = Long.toHexString(tagValue).toUpperCase();
if (tag.contentEquals("DAAD046F62ADA900")) {
startScanning();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (!tag.contains("DAAD046F62ADA900")) {
String tag2 = null;
long tagValue2 = ByteBuffer.wrap(receivedTag).getLong();
tag2 = Long.toHexString(tagValue2).toUpperCase();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
r.play();
int i = 0;
for (Part part : mParts) {
if(part.getCode().contains(tag2)) {
part.setScan(true);
part.setScanCounter(part.getScanCounter() + 1);
i++;
notifyDataSetChanged();
}
}
if(i==0){
Intent intent = new Intent(getContext(),AddActivity.class);
intent.putExtra("tag",tag2);
mActivity.startActivityForResult(intent,2);
}
}
}
}
notifyDataSetChanged();
}
} else {
Toast.makeText(getContext(), R.string.plug_scanner, Toast.LENGTH_SHORT).show();
}
}
Please, help.
in your doInBackground you do:
mActivity.runOnUiThread(new Runnable() {
That defeats the purpose and you do not execute on the background anymore - you are on the main-thread and so block the UI
This Line of your code
mActivity.runOnUiThread(new Runnable() {
Runs on UI thread you should return result in doinbackground and then use it in onPostExecute which runs on UI thread. doInBackground is made to run on background not on UI thread but you forcing it to run on UI thread

Transferring data from bluetooth to the android app

I have the following code in android studio, we have a arduino with a bluetooth module HC-05 and we are trying to send a data from a sensor via the bluetooth to the android app:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
btnOn = (Button) findViewById(R.id.measure);
sensorView0 = (TextView) findViewById(R.id.temp);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBlueToothState();
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
Toast.makeText(getBaseContext(), "Start Measuring", Toast.LENGTH_SHORT).show();
}
});
}
void openBT() throws IOException {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("%"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
int dataLength = dataInPrint.length(); //get length of data received
if (recDataString.charAt(0) == '*') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, endOfLineIndex); //get sensor value from string between indices 1-5
sensorView0.setText( sensor0 ); //update the textviews with sensor values
}
recDataString.delete(0, recDataString.length()); //clear all string data
dataInPrint = " ";
}
}
}
};
beginListenForData1();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 1000);//Message will be delivered in 1 second.
// myLabel.setText("Bluetooth Opened");
}
void beginListenForData1() {
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInputStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
});
workerThread.start();
}
private Runnable mMyRunnable = new Runnable()
{
#Override
public void run()
{
//Change state here
}
};
private void CheckBlueToothState() {
if (mBluetoothAdapter == null) {
} else {
if (mBluetoothAdapter.isEnabled()) {
if (mBluetoothAdapter.isDiscovering()) {
} else {
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-05")) {
mmDevice = device;
break;
}
}
try {
openBT();
}
catch (IOException ex) {
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();};
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == REQUEST_ENABLE_BT) {
{CheckBlueToothState();
}
}
}
void sendData() throws IOException
{
String msg = "1";
msg += "\n";
mmOutputStream.write(msg.getBytes());
//myLabel.setText("Data Sent");
}
void sendData0() throws IOException
{
String msg = "0";
msg += "\n";
mmOutputStream.write(msg.getBytes());
//myLabel.setText("Data Sent");
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
sendData0();
} catch (IOException e) {
e.printStackTrace();
}
try {
closeBT();
} catch (IOException e) {
e.printStackTrace();
}
//System.exit(0);
this.finish();
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
}
}
The code works for the second time only, so when i press the button in the app for the first time it does not show the data, but when i press it at the second time it shows the data, why is that happening?

Android bluetooth connection throwing read failed, socket might closed or timeout, read ret android

I am trying to communicate from android to a microprocessor controlled device, which uses HC-05, I have tried every possible solution, but btSocket.connect() is throwing
read failed, socket might closed or timeout, read ret android
Relevant code snippet is provided below:-
/**
* Sends the data Over BlueTooth
* #param data
* bytes which is to be send to the bibox.
*
* */
private void sendDataToBlueTooth(byte[] data){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String mMacChecking = pref.getString("BL", "bl");
if (!mMacChecking.equals("bl")) {
// Intent in = new Intent(getApplicationContext(), DataSendReceive.class);
// in.putExtra("isBtRemoteData", true);
// in.putExtra("bData", data);
// startActivity(in);
final SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
this.mDeviceMACAddress = pre.getString("BL", "");
this.mSendArray = data;
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
this.mHandler = new Handler() {
#SuppressLint("ShowToast")
#Override
public void handleMessage(final android.os.Message msg) {
if (msg.what == 1) {
mConnectStatus = true;
for (int i = 0; i < mSendArray.length; i++) {
write(mSendArray[i]);
}
String str = Arrays.toString(mSendArray);
Log.d("", str);
//Added an alert dialog to show the data..
// To activate the alert, put the below 3 lines inside the on click of the OK button...
onBackPressed();
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
} else if (msg.what == 2) {
// Set button to display current status
// connectStat = true;
final byte[] readBuf = (byte[]) msg.obj;
System.out.println("InHandler - ");
String receivedString = "";
for (final byte b : readBuf) {
// `byte` to `Byte`
final int temp = b;
final String tempString = String.valueOf(temp);
receivedString = receivedString.concat("," + tempString);
}
Log.d("received string", receivedString);
for (final byte element : readBuf) {
System.out.print(element + ",");
}
// System.out.println("" + readBuf);
} else if (mBluetoothAdapter.isEnabled()) {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
// Connection failed
mFailToast.show();
/* Intent scan = new Intent(getApplicationContext(), BluetoothDeviceDiscover.class); */
finish();
// startActivity(scan);
}
}
};
mFailToast = Toast.makeText(this, "Failed to connect please on " + this.mDeviceMACAddress + " or scan for new device", Toast.LENGTH_SHORT);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (this.mBtSocket != null) {
this.mBtSocket.close();
}
} catch (final IOException e2) {}
}
public void write(final byte arr2) {
if (this.mConnectStatus == true) if (this.mOutStream != null) {
try {
this.mOutStream.write(arr2);
} catch (final IOException e) {
showToast(getString(R.string.dataNotSendMessage), false);
}
} else {
showToast(getString(R.string.switchOnBlueToothDevice), false);
}
}
public void connectTOdevice() {
this.mConnectThread = new ConnectThread(this.mDeviceMACAddress);
this.mConnectThread.start();
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
boolean isUnpairToastToBeDisplayed = true;
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String DEVICE_PIN = getString(R.string.device_pin);
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals("android.bluetooth.device.action.BOND_STATE_CHANGED")) {
byte[] pin;
try {
pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, DEVICE_PIN);
BluetoothDevice.class.getMethod("setPin", byte[].class).invoke(device, pin);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
//Continue work here....
//If the number of paired devices greater than 3, unpair everything except the current one...
//Causing problem in lenovo tablet...
//Problem :- Tablet hang for more than 4 paired devices...
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices;
mPairedDevices = btAdapter.getBondedDevices();
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String deviceAddress = pref.getString("BL", "NoDevice");
if (mPairedDevices.size() > MAX_ALLOWED_PAIRED_DEVICES) {
// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (final BluetoothDevice deviceForLoop : mPairedDevices) {
//if the device for loop doesn't match the latest saved address...
//unpair the device...
if(!deviceAddress.equals(deviceForLoop.getAddress())){
isUnpairToastToBeDisplayed = false;
unpairDevice(deviceForLoop);
isUnpairToastToBeDisplayed = true;
}
}
}
showToast(getString(R.string.pairedToastMessage),false);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(!isUnpairToastToBeDisplayed)
showToast(getString(R.string.unpairedToastMessage),false);
}
}
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Intent i = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(i);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
}
};
private void unpairDevice(final BluetoothDevice device) {
try {
final Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (final Exception e) {
// Log.e(TAG, e.getMessage());
}
}
public class ConnectThread extends Thread {
private final String address;
private boolean connectionStatus;
ConnectThread(final String MACaddress) {
this.address = MACaddress;
this.connectionStatus = false;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(this.address);
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
try {
SPP_UUID = device.getUuids()[0].getUuid();
BluetoothSocket tmp = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
mBtSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
} catch (final IOException e) {
this.connectionStatus = false;
} catch (Exception e) {
}
} catch (final IllegalArgumentException e) {
this.connectionStatus = false;
}
try {
mBtSocket.connect();
this.connectionStatus = true;
} catch (final IOException e1) {
try {
mBtSocket.close();
Log.d("check", "check");
} catch (final IOException e2) {}
}
// Create a data stream so we can talk to server.
try {
mOutStream = mBtSocket.getOutputStream();
} catch (final IOException e2) {
this.connectionStatus = false;
}
// Send final result
if (this.connectionStatus) {
mHandler.sendEmptyMessage(1);
} else {
mHandler.sendEmptyMessage(0);
}
}
}
}
I found the answer in the following question:-
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Actually I had to use reflection only on the fall back, ie, inside the catch when the connect fails.

Categories

Resources