如何在android中停止Handler

时间:2013-04-11 12:45:46

标签: android handler android-handler

我已经创建了一个Android应用程序,当一个按钮点击处理程序时,将每隔2秒激活一个烤面包机。同样在另一方面,我有一个停止按钮,我想从中点击

停止正在运行的线程

这是我的代码

private final int  FIVE_SECONDS = 2000;


    public void scheduleSendLocation() {
        handler.postDelayed(new Runnable() {
            public void run() {
                sendLocation();          // this method will contain your almost-finished HTTP calls
                handler.postDelayed(this, FIVE_SECONDS);
            }
        }, FIVE_SECONDS);
    }


    protected void sendLocation() {
        Toast.makeText(getApplicationContext(), "Your Location is ", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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

        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
                scheduleSendLocation();

            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
        // what to write here
            }
        });

    }

2 个答案:

答案 0 :(得分:5)

尝试调用以下代码

    stop.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {        
            handler.removeCallbacks(runnable);
        }
    });

runnable是您在调用postDelayed时添加的runnable。将删除runnable中的任何待处理帖子,这些帖子位于邮件队列中。

答案 1 :(得分:0)

试试这个:

stop.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {        
             myHandlerThread.interrupt();
             myHandlerThread = null;
        }
    });