Reputation: 3070
I have a thread in my callback function as follows:
@Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something
}
}, 2000);
}
});
}
I will to close the the above thread when I press the back button or onDestroy. How can I do it. Thank you
@Override
public void onBackPressed() {
// Close or distroy the thread
}
@Override
public void onDestroy() {
// Close or distroy the thread
}
Upvotes: 0
Views: 2735
Reputation: 4220
I'm mostly use thread in this way.See its independent in activity
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
holdConnectionHandler.sendEmptyMessage(0);
}
Handler holdConnectionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// do some work
holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
}
};
@Override
public void onDestroy() {
super.onDestroy();
holdConnectionHandler.removeCallbacksAndMessages(null);
// or
holdConnectionHandler.removeMessages(0);
}
}
Thanks hope this will help you
Upvotes: 1
Reputation: 13593
Please do this like
private Handler handler;
private Runnable runnable;
@Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
@Override
public void run() {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
//Do something
}
};
handler.postDelayed(runnable, 2000);
}
});
}
and
@Override
public void onBackPressed() {
if (handler != null && runnable != null) {
handler.removeCallbacks(runnable);
}
}
and same in onDestroy();
Upvotes: 1