I'm trying to connect to a embedded device which actually works but when i'm connecting it consumes alot of resources and the app comes to a halt which after some while will respond in a force quit or wait dialog.
Read somewhere that a backgroundthread would be the way to go about this but I don't know how to implement it. Should I do it as a service?.. or? Real-time programming was a long time ago for me and some help from you guys would be appreciated.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carsetup);
car1 = (TextView) findViewById(R.id.carsetuptest1);
car2 = (TextView) findViewById(R.id.carsetuptest2);
car3 = (TextView) findViewById(R.id.carsetuptest3);
Intent i = getIntent();
selectedcar = (CarModule) i.getParcelableExtra("car");
car1.setText(selectedcar.getRealname());
car2.setText(selectedcar.getRealname());
car3.setText(selectedcar.getAddress());
try {
for (int c = 0; c < 3; c++) {
connectBluetooth();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectBluetooth() throws Exception {
if (connected) {
return;
}
BluetoothDevice car = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice(selectedcar.getAddress());
Method m = car.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
sock = (BluetoothSocket)m.invoke(car, Integer.valueOf(1));
Log.d(selectedcar.getRealname(), "++++ Connecting");
sock.connect();
Log.d(selectedcar.getRealname(), "++++ Connected");
}
}
@Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
super.onBackPressed();
}
It's at sock.connect()
it fails. So how would I go about this problem?
EDIT: So I've been exploring different options but it still locks up. Now I've tried to implement the threads as Runnable and execute them through a Handler in the following manner:
void connectBluetooth(boolean nextstage, IOException e1){
if(!nextstage){
showDialog(DIALOG_BT_ADDING);
new Handler().post(new ConnectThread(ThreadHandler, selected_car.getDevice()));
}
else{
if(e1 != null){
new Handler().post(new BluetoothCheckThread(ThreadHandler,mBluetoothAdapter,
5000, car_bt, after_bt));
search_dialog.dismiss();
}
else{
showDialog(DIALOG_BT_ADDING_FAILED);
}
}
}
ConnectThread
implements Runnable
and has run()
overidden. The problem is that the UI thread is still locked up and I cannot figure out how.
ThreadHandler
is located in the running Activity
:
Handler ThreadHandler = new Handler (){
public void handleMessage(Message msg) {
Log.i("MESSAGEHANDLER", "Message "+ msg.arg1 + " recieved" );
if(msg.arg1 == 0){
launchAndPrepare();
}
if(msg.arg1 == 1 || msg.arg1 == 2){
search_dialog.dismiss();
showDialog(DIALOG_BT_ADDING_FAILED);
}
}
};
I'm on the verge of trying another approach like AsyncTask
. Will that work on the application above? Or have I done something incorrect in my current implementation?