20

Android の LocationManager requestLocationUpdates を使用しようとしています。ブロードキャストレシーバーにある実際の位置オブジェクトを抽出しようとするまで、すべてが機能しています。Android LocationManager を requestLocationUpdates に渡す前にカスタム インテントに「エクストラ」を具体的に定義して、それをインテントに追加する方法を認識させる必要がありますか。放送受信機への意図?

私のコードは次のようになります。

Intent intent = new Intent("com.myapp.swarm.LOCATION_READY");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
    0, intent, 0);

//Register for broadcast intents
int minTime = 5000;
int minDistance = 0;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
    minDistance, pendingIntent);

マニフェストで次のように定義されている放送受信機があります。

<receiver android:name=".LocationReceiver">
    <intent-filter>
        <action android:name="com.myapp.swarm.LOCATION_READY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

また、ブロードキャスト レシーバー クラスは次のようになります。

public class LocationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    //Do this when the system sends the intent
    Bundle b = intent.getExtras();
    Location loc = (Location)b.get("KEY_LOCATION_CHANGED");

    Toast.makeText(context, loc.toString(), Toast.LENGTH_SHORT).show(); 
    }
}

「loc」オブジェクトが null になります。

4

2 に答える 2

20

OK、放送受信機コードの KEY_LOCATION_CHANGED を次のように変更することで、なんとか修正できました。

public class LocationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    //Do this when the system sends the intent
    Bundle b = intent.getExtras();
    Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);

    Toast.makeText(context, loc.toString(), Toast.LENGTH_SHORT).show(); 
    }
}
于 2010-01-02T07:53:49.900 に答える
14

私はあなたが提案したソリューションをコーディングしてテストしようとしました.近接アラートとロケーションオブジェクトを運ぶインテントに関する同様の問題に直面しているためです. あなたが提供した情報によると、BroadcastReceiver 側で null オブジェクトの取得を克服することができました。あなたが気づいていないかもしれないのは、インテントが最初に作成された場所と同じ場所を受け取る必要があるということです (インテント キャッシングの問題としても見られます)。

この問題を克服するために、ここで多くの人々によって提案されているように、FLAG_CANCEL_CURRENT を使用しました。これは非常にうまく機能し、新鮮な (そしてジューシーな :P) 位置値をフェッチします。したがって、保留中のインテントを定義する行は次のようになります。

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

ただし、次の場合はこれを無視できます。

  • あなたの目的は、場所の値を一度受け取ることでした
  • 投稿に表示されていない他の方法でそれを克服することができました
于 2010-12-02T18:59:44.047 に答える