It sounds like the activity finishes its lifecycle before the Handler executes the code. You can manage a handler.post(runnable) by creating an instance member for the handler and runnable, then managing the handler in the Activity Lifecycle methods.
private Handler myHandler;
private Runnable myRunnable = new Runnable() {
@Override
public void run() {
//Do Something
}
};
Start the runnable with handler.post.
protected void onStart() {
super.onStart();
myHandler = new Handler();
myHandler.post(myRunnable);
}
If the runnable hasn't executed by the time onStop is called, we don't want to run it.
Remove the callback in the onStop method:
protected void onStop() {
super.onStop();
mHandler.removeCallbacks(myRunnable);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…