How To Stop The Thread In Android?
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.');
Solution 1:
Please do this like
privateHandler handler;
privateRunnable runnable;
@OverridepublicvoidonConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
handler = newHandler();
runnable = newRunnable() {
@Overridepublicvoidrun() {
//Do something
}
};
handler.postDelayed(runnable, 2000);
}
});
}
and
@OverridepublicvoidonBackPressed() {
if (handler != null && runnable != null) {
handler.removeCallbacks(runnable);
}
}
and same in onDestroy();
Solution 2:
I'm mostly use thread in this way.See its independent in activity
publicclassTestActivityextendsActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
holdConnectionHandler.sendEmptyMessage(0);
}
Handler holdConnectionHandler = newHandler() {
publicvoidhandleMessage(android.os.Message msg) {
// do some work
holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
}
};
@OverridepublicvoidonDestroy() {
super.onDestroy();
holdConnectionHandler.removeCallbacksAndMessages(null);
// or
holdConnectionHandler.removeMessages(0);
}
}
Thanks hope this will help you
Post a Comment for "How To Stop The Thread In Android?"