0

我的主要活动中有以下代码(注意:GPSTracker在此应用程序中有效):

    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仅显示一次(最后一次迭代)。你能帮我解决这个问题吗?提前致谢。

4

2 回答 2

1

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

上面的代码不是每五秒循环一次,它会连续循环,但只会每五秒递增一次计数器……这是一种非常低效的创建时间延迟的方法,因为在循环运行时不会发生任何其他事情。(即使你在单独的线程上运行它仍然不是一个好策略。)

而是使用 LocationManager requestLocationUpdates,它将使用回调,以便您的应用程序可以在更新之间执行操作。几个快速说明:

  • 了解 GPS 可能无法每 5 秒修复一次,而且此间隔非常短,因此请谨慎使用,否则会耗尽电池电量。
  • 一些 pre-Jelly Bean 设备可能不会观察到该minTime参数,但您可以自己强制执行您的时间参数,正如我在Android Location Listener call very often中所描述的那样。

除此之外,您使用现有代码,但我推荐使用 Handler 和 Runnable,如下所示:

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);
于 2013-02-24T18:16:28.013 回答
0

一个问题是这种方法会执行“忙等待”,我怀疑这会阻止显示吐司。尝试做一个 sleep() 等到下一个 Toast 的时间:

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

}
于 2013-02-24T18:20:33.643 回答