如何使用按钮切换停止正在运行的线程(android应用程序)

如何使用按钮切换停止正在运行的线程(android应用程序),android,Android,我终于让我的应用程序工作,我只有一个问题,我想纠正 我有一个按钮,它控制一个线程,该线程在后台运行一个耦合函数。当达到某个值时,后台函数最终会停止线程。我正在做的是再次按下相同的按钮,手动停止线程。目前我只能启动线程并等待它自己完成。我可以在应用程序中做其他事情,所以线程是独立运行的,我只想手动杀死它 public void onMonitorClick(final View view){ if (isBLEEnabled()) { if (!isDeviceCo

我终于让我的应用程序工作,我只有一个问题,我想纠正

我有一个按钮,它控制一个线程,该线程在后台运行一个耦合函数。当达到某个值时,后台函数最终会停止线程。我正在做的是再次按下相同的按钮,手动停止线程。目前我只能启动线程并等待它自己完成。我可以在应用程序中做其他事情,所以线程是独立运行的,我只想手动杀死它

    public void onMonitorClick(final View view){
    if (isBLEEnabled()) {
        if (!isDeviceConnected()) {
                // do nothing
        } else if (monitorvis == 0) {
            showMonitor();
            DebugLogger.v(TAG, "show monitor");
            //monitorStop = 4;
            Kill.runThread();         // I want a function here that would kill the 
                                     // thread below, or is there something that 
                                     // can be modified in runThread()?
                                     // I did try Thread.Iteruppted() without luck
            shutdownExecutor();

        } else if (monitorvis == 1) {
            hideMonitor();
            DebugLogger.v(TAG, "hide monitor");
            monitorStop = 0;
            runThread(); //The running thread that works great on its own

        }
    } 
    else {
        showBLEDialog();
    }
}



private void runThread() {

    new Thread() {
        int i;
        public void run() {
            while (monitorStop != 3) {  //This is where the thread stops itself 
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ((ProximityService.ProximityBinder) getService()).getRssi();
                            rssilevel = ((ProximityService.ProximityBinder) getService()).getRssiValue();
                            mRSSI.setText(String.valueOf(rssilevel) + "dB");
                            detectRange(rssilevel);
                        }
                    });
                    Thread.sleep(750);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

首先,您可以简单地设置monitorStop=3,这将导致线程在超时完成后最终停止

问题是,我想如果你再按一下按钮,或者你的代码在将来某个时候修改了monitorStop,那么你想要的thead可能还活着。ie:monitorStop将需要保持等于3至少750ms,以确保线程将完成其循环并死亡


正确的方法是使用自己的monitorStop参数将线程创建为一个新类。创建线程时,将保留对它的引用,并修改线程的monitorStop参数。这样线程就可以不间断地完成。如果要创建新线程,那么这不会影响旧线程的正确完成。

为什么不使用处理程序?它将在一个新线程中开始您的工作,当您想要停止它时,只需使用removeCallbacks方法早在Java早期就有一种方法可以在线程上调用stop,但是这种方法存在问题,并且不推荐使用。这里有一篇关于为什么的精彩文章: