2013-02-24 59 views
0

我在我的主要活動如下代碼土司循環無法正常顯示

double latitude, longitude; 
    gps = new GPSTracker(MainActivity.this); 
    if(gps.canGetLocation()){ 
     latitude = gps.getLatitude(); 
     longitude = gps.getLongitude(); 
     Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
    } 
    else{ 
     gps.showSettingsAlert(); 
    } 

我想創建一個循環,這將在一定的時間間隔顯示Toast與我目前的位置。從來就嘗試這樣做:

double latitude, longitude; 
    long currentTime = System.currentTimeMillis(); 
    long myTimestamp = currentTime; 
    int i = 0; 
    gps = new GPSTracker(MainActivity.this); 
    while(i < 5) 
    { 
     myTimestamp = System.currentTimeMillis(); 
     if((myTimestamp - currentTime) > 5000) 
     { 
      i++; 
      currentTime = System.currentTimeMillis(); 
      if(gps.canGetLocation()){ 
       latitude = gps.getLatitude(); 
       longitude = gps.getLongitude(); 
       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
      }else{ 
       gps.showSettingsAlert(); 
      } 
     } 
    } 

有了這個代碼,Toast僅示出一個時間(最後迭代)。你能幫我解決這個問題嗎?提前致謝。

+0

嘗試打印顯示的「I」舉杯 – nayab 2013-02-24 18:06:28

+0

就像我說的,最後一次迭代過程中顯示吐司(I = 5) – Tom11 2013-02-24 18:08:20

+0

雙檢查你的條件.. – moDev 2013-02-24 18:10:49

回答

1

我希望每次迭代都會顯示它(例如每隔5秒)。

上面的代碼不循環每五秒鐘,它不斷地循環,但只增加你的櫃檯每五秒鐘......這是創建的時間延遲,因爲沒有別的可以同時循環發生一個非常低效的方法運行。 (即使你在單獨的線程上運行它,它仍然不是很好的策略。)

取而代之,使用LocationManager的requestLocationUpdates,它將使用回調函數,以便您的應用程序可以在更新之間進行操作。一對夫婦的快速說明:

  • 記者瞭解到,GPS可能無法得到修復每五秒鐘,並在該時間間隔是非常短的所以應謹慎使用,否則你會耗盡電量下降。
  • 一些預果凍豆設備可能不遵守minTime參數,但你可以執行你自己的時間參數作爲我Android Location Listener call very often形容。

所有這一切不談,你用你現有的代碼,但我推薦一個處理器和運行的,就像這樣:

handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     // Fetch your location here 

     // Run the code again in about 5 seconds 
     handler.postDelayed(this, 5000); 
    } 
}, 5000); 
0

的一個問題是,這種方法確實一個「忙等待」,我猜想,這可以防止烤麪包被顯示出來。試着做一個sleep()要等到它的時間爲下吐司:

public void sleepForMs(long sleepTimeMs) { 
    Date now = new Date(); 
    Date wakeAt = new Date(now.getTime() + sleepTimeMs); 
    while (now.before(wakeAt)) { 
     try { 
      long msToSleep = wakeAt.getTime() - now.getTime(); 
      Thread.sleep(msToSleep); 
     } catch (InterruptedException e) { 
     } 

     now = new Date(); 
    } 

} 
+0

您仍在阻止UI線程。你應該把代碼放在一個單獨的線程中。 – 2013-02-24 18:23:16