簡體   English   中英

我如何加入該線程以使其停止?

[英]How do I join the thread to stop it?

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()加入線程。 解決方案將有所幫助。

使timerThread為類成員,而不是語言環境變量,通過這種方式,您應該從onLocationChanged方法訪問它

改用AsyncTask,存儲Future並自己停止線程。

如果這不是家庭作業,那么我看不到join() 更重要的是,當您嘗試將UI線程與任意線程連接時,會有效地引起ANR

要么:

  1. 創建您自己的擴展Thread的類,實現您的terminate()方法,然后在需要時調用它。

  2. 創建擴展AsyncTask的自己的類,實現LocationListener,並使用其onProgressUpdate()方法。

您只需在Activity中聲明一個成員:

private Thread mTimerThread = null;

然后在您的onCreate()中替換:

final Thread timerThread = new Thread() {

mTimerThread = new Thread() {

並在onLocationChanged中:

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

實現您想要的。

但是,正如其他人提到的那樣,我也建議您使用自定義AsyncTask因為這將是您情況下最清晰的線程處理方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM