0

我的回调函数中有一个线程,如下所示:

@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);
        }
    });
}

当我按下后退按钮或 onDestroy 时,我将关闭上述线程。我该怎么做。谢谢

@Override
public void onBackPressed() {
    // Close or distroy the thread
 }
@Override
public void onDestroy() {
    // Close or distroy the thread
 }
4

2 回答 2

1

我主要以这种方式使用线程。查看它的独立活动

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);

}
}

谢谢希望这会对你有所帮助

于 2016-09-15T15:18:01.200 回答
1

请这样做

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);
    }
});
}

@Override
public void onBackPressed() {
if (handler != null && runnable != null) {
        handler.removeCallbacks(runnable);
    }
 }

和 onDestroy() 一样;

于 2016-09-15T15:23:57.640 回答