停止handler.postDelayed()


109

我通过new Handler()。postDelayed(new Runnable().....来调用多个Handler。当我单击返回时如何停止它?

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

我的问题是我的处理程序没有类似“ myHandler”的名称。我该如何处理?

感谢帮助!

现在我得到了这些错误:

03-28 17:47:03.662: E/AndroidRuntime(1961): FATAL EXCEPTION: main
03-28 17:47:03.662: E/AndroidRuntime(1961): java.lang.NullPointerException
03-28 17:47:03.662: E/AndroidRuntime(1961):     at de.basti12354.tage.uebungen.Tag1.onBackPressed(Tag1.java:120)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.app.Activity.onKeyUp(Activity.java:2159)
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)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.os.MessageQueue.nativePollOnce(Native Method)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.os.MessageQueue.next(MessageQueue.java:132)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.os.Looper.loop(Looper.java:124)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at java.lang.reflect.Method.invokeNative(Native Method)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at java.lang.reflect.Method.invoke(Method.java:525)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-28 17:47:03.662: E/AndroidRuntime(1961):     at dalvik.system.NativeStart.main(Native Method)

Answers:


196

您可以使用:

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

或者您可以使用:

 handler.removeCallbacksAndMessages(null);

文件

公共最终无效removeCallbacksAndMessages(对象令牌)

在API级别1中添加删除obj为令牌的回调和已发送消息的所有未决帖子。如果token为null,则将删除所有回调和消息。

或者,您也可以这样做:

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

然后:

handler.removeCallbacks(myRunnable);

文件

公共最终无效removeCallbacks(Runnable r)

在API级别1中添加删除消息队列中所有Runnable r的未决帖子。

公共最终void removeCallbacks(Runnable r,对象令牌)

编辑:

更改此:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

至:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

因为您拥有以下内容。之前onCreate已经声明过,但是您先重新声明然后初始化它onClick才能生成NPE。

Handler handler; // declared before onCreate
Runnable myRunnable;

1
已经添加了handler.removeCallbacks(myRunnable); 到我的onBackPressed()是吗?
basti12354 2014年

1
@ user3433232使用它来停止运行
Raghunandan 2014年

1
您能否看一下我的代码,我尝试使用您的帮助?,但是现在我得到了错误,您可以在我的帖子中看到。
basti12354 2014年

1
@ user3433232检查编辑。您的处理程序为空。您在通向NPE的onClick中重新声明了它
Raghunandan 2014年

6
我正在使用API​​ 16,并且handler.removeCallbacks(runnable)无法正常工作。但是handler.removeCallbacksAndMessages(null); 工作感谢
mismanc 2015年

12

您可以定义一个布尔值,并在要停止处理程序时将其更改为false。像这样..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

10

这可能很旧,但是对于那些寻找答案的人来说,可以使用此...

public void stopHandler() {
   handler.removeMessages(0);
}

干杯


2
  Boolean condition=false;  //Instance variable declaration.

 //-----------------Inside oncreate--------------------------------------------------- 
  start =(Button)findViewById(R.id.id_start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                starthandler();

                if(condition=true)
                {
                    condition=false;
                }


            }
        });

        stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stophandler();

            }
        });


    }

//-----------------Inside oncreate---------------------------------------------------

 public void starthandler()
    {

        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


                if(!condition)
                {
                    //Do something after 100ms 


                }

            }
        }, 5000);

    }


    public void stophandler()
    {
        condition=true;
    }

请解释为什么这段代码回答了这个问题。
安德烈·库尔

假设您在XML开始和停止按钮中都有2个按钮。该代码演示了如何通过单击开始按钮来启动处理程序以及如何通过停止按钮来停止处理程序的演示。
vinay shetty

它可以工作,但可运行对象仍在后台运行。
ColdTuna
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.