Stop handler.postDelayed() (SHPD)

I call some Handlers with  Handler().postDelayed(new Runnable()..... How can I stop them when I click the back button?

public class MyActivity extends AppCompatActivity implements OnClickListener {

    private Button btn;
    private Handler handler;
    private Runnable myRunnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        btn = (Button) findViewById(R.id.trainingsstart);
        btn.setOnClickListener(this);   
    }

    @Override
    public void onClick(View v) {
        Handler handler =  new Handler();
        Runnable myRunnable = new Runnable() {
            public void run() {
                // Things to be done
            }
        };

        handler.postDelayed(myRunnable, 3000);
    }

    @Override 
    public void onBackPressed() { 
        super.onBackPressed();
        handler.removeCallbacks(myRunnable);
    }   
}

I have a problem that my Handler doesn't have a name like "myHandler". How can I solve it? Thanks for your help! Now I get this error:

03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.KeyEvent.dispatch(KeyEvent.java:2647)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.app.Activity.dispatchKeyEvent(Activity.java:2389)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)

Solution

You can do it in the following way:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

or in this way:

handler.removeCallbacksAndMessages(null);

The above method may be outdated, please update it in this way:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

then stop in this way:

handler.removeCallbacks(myRunnable);

Post a Comment

Previous Next

نموذج الاتصال