如何加入线程来阻止它?

时间:2013-11-07 12:40:47

标签: java android multithreading

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mProgressBar = (ProgressBar)findViewById(R.id.adprogress_progressBar);


    final Thread timerThread = new Thread() {

        private volatile boolean running = true;
        public void terminate() {
            running = false;
        }
        @Override
        public void run() {
            while(running) {
            mbActive = true;
                try {
                int waited = 0;
                    while(mbActive && (waited < TIMER_RUNTIME)) {
                    sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                running=false;
                }
            }
        }
    };
    timerThread.start();
}

public void onLocationChanged(Location location) {

    if (location != null) {

        TextView text;
        text = (TextView) findViewById(R.id.t2);
        String str= "Latitude is " + location.getLatitude() + "\nLongitude is " + location.getLongitude();

        text.setText(str);
        text.postInvalidate();
    }

}

如何从onLocationChanged中停止onCreate中的线程?一旦GPS提供坐标,我需要停止进度条。我需要使用join()加入线程。解决方案将有所帮助。

4 个答案:

答案 0 :(得分:0)

使timerThread成为类成员而不是语言环境变量,这样你应该从onLocationChanged方法访问它

答案 1 :(得分:0)

使用AsyncTask,存储Future并自行停止线程。

答案 2 :(得分:0)

如果这不是家庭作业,那么我认为没有必要join()。当您尝试使用任意线程加入UI线程时,更有效的是,有效地获取ANR

或者:

  1. 创建自己的类Thread,实现terminate()方法,然后随时调用。

  2. 创建自己的类AsyncTask,实现LocationListener,并使用其onProgressUpdate()方法。

答案 3 :(得分:0)

您只需在您的活动中声明一名成员:

private Thread mTimerThread = null;

然后在你的onCreate()替换:

final Thread timerThread = new Thread() {

mTimerThread = new Thread() {

并在onLocationChanged:

if (mTimerThread != null && mTimerThread.isAlive()) {
    mTimerThread.terminate();
}

实现你想要的目标。

但是,正如其他人所提到的,我还建议您使用自定义AsyncTask,因为在您的情况下,这将是最明确的线程方式。

相关问题