0
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();
    }

}

onCreate のスレッドを onLocationChanged から停止するにはどうすればよいですか? GPS が座標を提供したら、プログレスバーを停止する必要があります。join() を使用してスレッドに参加する必要があります。解決策が役立ちます。

4

4 に答える 4

0

timerThread をロケール変数ではなくクラス メンバーにします。このようにして、onLocationChanged メソッドからアクセスする必要があります。

于 2013-11-07T13:07:57.503 に答える
0

代わりに AsyncTask を使用し、Future を保存してスレッドを自分で停止します。

于 2013-11-07T13:09:44.680 に答える
0

Activity で member を宣言するだけです。

private Thread mTimerThread = null;

次に、 onCreate() で置き換えます:

final Thread timerThread = new Thread() {

mTimerThread = new Thread() {

および onLocationChanged で:

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

あなたが望むものを達成するために。

ただし、他の人が述べたように、カスタムAsyncTaskを使用することをお勧めします。

于 2013-11-07T13:18:54.130 に答える
0

これが在宅ワークの割り当てでない場合は、する必要はないと思いますjoin()。UI スレッドを任意のスレッドに結合しようとしている場合はなおさらで、ANRが効果的に発生します。

また:

  1. を拡張する独自のクラスを作成Threadし、メソッドを実装してterminate()から、いつでも呼び出すことができます。

  2. AsyncTaskを拡張して LocationListener を実装する独自のクラスを作成し、そのonProgressUpdate()メソッドを使用します。

于 2013-11-07T13:14:10.323 に答える