Nazerke
Nazerke

Reputation: 2098

Handler is keeping activity from finishing

I have declared private Handler mHandler = new Handler(); and used this handler many times in my activity. For example:

        // fade out view nicely after 5 seconds
        mHandler.postDelayed(new Runnable() {
            public void run() {
                tview.setText(null);
            }
        }, 4000);

or

mHandler.postDelayed(new Runnable() {
public void run() {
    tview.setText(null);
    parentLayout.findViewById(R.id.fireplace).setVisibility(View.GONE);
    parentLayout.removeView(findViewById(R.id.fireplace));
    water_room.setVisibility(View.VISIBLE);
    playSound(fountainSoundID); 
}
}, 3000);

Now, if I go back (via pressing back button) when this handler has already started it's action, because of this handler activity is not finishing.I want mHandler stop whatever it is doing and not keep the activity from finishing. How do I do that?

Upvotes: 2

Views: 2795

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33505

How do I do that?

I'm little confused what are you trying to say but if i understood it correctly, you need to override onBackPressed() method and here you'll stop Handler and finish Activity.

Pseudo-code:

@Override
public void onBackPressed() {
   // stop Handler
   handler.removeCallbacks(runnable);
   // to stop anonymous runnable use handler.removeCallbacksAndMessages(null);
   finish();
}

Since your Runnable is anonymous you need to use second approach:

handler.removeCallbacksAndMessages(null);

If you're confused from this method, here is its doc:

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Upvotes: 5

Niko
Niko

Reputation: 8153

Get pointer of the Runnable and try following:

@Override
public void onBackPressed() {
    myHandler.removeCallbacks(myRunnable);
    finish();
}

Upvotes: 0

Related Questions