1

我已经创建了一个 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
            }
        });

    }
4

2 回答 2

5

尝试调用以下代码

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

runnable您在调用 postDelayed 时添加的可运行对象在哪里。消息队列中的任何待处理帖子都runnable将被删除。

于 2013-04-11T12:49:40.847 回答
0

尝试这个:

stop.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {        
             myHandlerThread.interrupt();
             myHandlerThread = null;
        }
    });
于 2013-04-11T12:49:21.187 回答