I have created a handler in my app. The functionality of this handler is that if it doesn't detect any user input for 15 seconds(touch,drag etc) it will launch a new activity. Here is the code for the same.
public void startHandler(long duration) {
if (handler != null) {
handler.postDelayed(r, duration);
Log.d("handler", "inside if");
} else {
Log.d("handler", "inside else");
handler = new Handler();
r = new Runnable() {
@Override
public void run() {
Log.d("handler", "handler running");
// TODO Auto-generated method stub
Intent intent = new Intent(ActivityProducts.this, ActivityVideo.class);
startActivity(intent);
}
};
handler.postDelayed(r, duration);
}
}
Here the duration is dynamic and is fetched from the server.
Below is the code to stop handler.
public void stopHandler() {
if (handler != null) {
handler.removeCallbacks(r);
handler.removeCallbacksAndMessages(null);
handler = null;
}
}
And below is the code for starting handler
@Override
public void onUserInteraction() {
// TODO Auto-generated method stub
super.onUserInteraction();
Log.d("user", "interacted");
//stop first and then start
if (duration != 0) {
stopHandler();
startHandler(duration);
}
}
I am stopping the handler in all methods onPause,onStop and onDestroy. But the problem is that if I navigate to any other activity from this activity the start handler code still executes and takes me to the Video Activity.
So what is the proper way of stopping the handler?