循环中的Toast未正确显示

时间:2013-02-24 18:01:05

标签: android loops toast

我的主要活动中有以下代码(注意:此应用程序中的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仅显示一次(最后一次迭代)。你能帮帮我吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

  

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

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

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

  • 了解GPS可能无法每五秒钟进行一次修复,并且此间隔非常短,因此请谨慎使用它,否则您将耗尽电量。
  • 某些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);

答案 1 :(得分: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();
    }

}