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は、 は 1 回だけ (最後の繰り返し) 表示されます。これで私を助けてもらえますか?前もって感謝します。

4

2 に答える 2

1

繰り返しごとに(たとえば、5秒ごとに)表示したい。

上記のコードは 5 秒ごとにループするのではなく、継続的にループしますが、カウンターを 5 秒ごとにインクリメントするだけです... これは、ループの実行中に他に何も起こらないため、時間遅延を作成する非常に非効率的な方法です。(これを別のスレッドで実行したとしても、それはまだ良い戦術ではありません。)

代わりに、コールバックを使用する LocationManagerrequestLocationUpdatesを使用して、アプリが更新の間に何かを実行できるようにします。いくつかの簡単なメモ:

  • GPS が 5 秒ごとに修正を取得できない可能性があること、およびこの間隔が非常に短いことを理解してください。慎重に使用しないとバッテリーが消耗します。
  • Jelly Bean より前のデバイスの中には、パラメーターを監視しないものもありますが、 Android Location Listener call very oftenminTimeで説明しているように、時間パラメーターを自分で強制することができます。

それはさておき、既存のコードを使用しますが、次のように 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

1 つの問題は、このメソッドが「busy-wait」を実行することです。これにより、トーストが表示されなくなると思われます。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();
    }

}
于 2013-02-24T18:20:33.643 に答える