2012-01-27 23 views
3

我知道這種問題的存在,但我很困惑在這裏我使用這個代碼創建處理程序:requestLocationUpdates給出錯誤「無法裏面)線程已經不叫Looper.prepare(

public class NewWaitAppActivity extends Activity { 
    private Handler mHandler; 
    @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     mHandler = new Handler(); 
     lcmgr = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 
     Thread LocThread = new Thread(mLocationUpdater); 
     Log.d("TAG","About to start worker thread"); 
     LocThread.start(); 
} 

public void startTimer(View v) { 
     if (mStartTime == 0L) { 
      mStartTime = System.currentTimeMillis(); 
      mHandler.removeCallbacks(mUpdateTimeTask); 
      mHandler.postDelayed(mUpdateTimeTask, 100); 
     } 
    } 

private Runnable mUpdateTimeTask = new Runnable() { 
     public void run() { 
      final long start = mStartTime; 
      long millis = System.currentTimeMillis() - start; 
      int seconds = (int) (millis/1000); 
      int minutes = seconds/60; 
      seconds = seconds % 60; 

      TextView timer = (TextView) findViewById(R.id.time_elapsed); 

      if (seconds < 10) { 
       timer.setText("" + minutes + ":0" + seconds); 
      } else { 
       timer.setText("" + minutes + ":" + seconds); 
      } 

      mHandler.postDelayed(this, 1000); 
     } 
    }; 
LocationListener locationListener = new LocationListener() { 

     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      mStopTimer(); 
     } 
}; 


private Runnable mLocationUpdater = new Runnable(){ 
     public void run(){ 

      Log.d("TAG","Inside worker thread"); 
      lcmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
    } 
}; 
} 

我基本上試圖在位置更新時停止主線程的計時器,應用程序甚至沒有啓動,它在運行時提供了上面提到的錯誤,錯誤是由於requestLocationUpdates()造成的,在onLocationChanged()中調用stopTimer()。我該如何解決這個問題?

回答

3

當它本身是一個基於異步回調的機制時,需要從您創建的線程中調用「lcmgr.requestLocationUpdates(....)」是什麼?
只需在您的活動的onCreate()中移動此代碼,並且事情應該可以正常工作。

當你嘗試在一個線程內部創建一個處理程序時,這個錯誤並不是打算循環的(也就是說,不要調用Looper.prepare的線程,因爲你的棧跟蹤狀態也是這樣)。

關於這個錯誤的更多解釋也可以在這個網站上找到。
但這裏也給出了一個很好的解釋。
http://www.aviyehuda.com/2010/12/android-multithreading-in-a-ui-environment/

+0

。感謝您的迴應!至少應用程序運行。 – sgarg 2012-01-27 15:02:32

0

你不能訪問/生成事件線程特定的事件,而且你不需要在一個線程中查詢位置更新,而不是您可以使用服務來實現相同。

26

甚至不需要編寫複雜的解決方案,

locationManager.requestLocationUpdates(供應商,5000,0,myListener的,Looper.getMainLooper();

這會工作得很好

+1

感謝的人。它工作正常。 – 2017-07-06 13:49:32

+0

不幸的是,並沒有解決它對我。:( – Bungles 2017-07-31 18:51:33

+1

謝謝你。 – 2017-10-02 08:56:46

相關問題