問題描述
我正在嘗試使用 Android 的 LocationManager requestLocationUpdates.一切正常,直到我嘗試提取廣播接收器中的實際位置對象.我是否需要專門為我的自定義意圖定義附加",以便 Android LocationManager 在我將它傳遞給 requestLocationUpdates 之前知道如何將其添加到意圖中,或者它是否會創(chuàng)建附加捆綁包,無論它何時通過觸發(fā)廣播接收者的意圖?
I am trying to use Android's LocationManager requestLocationUpdates. Everything is working until I try to extract the actual location object that in my broadcast receiver. Do I need to specifically define the "extras" to my custom intent so that the Android LocationManager before I pass it to requestLocationUpdates so it knows how to add it into the intent, or will it create the extras-bundle regardless when it passes the fired intent to the broadcast receiver?
我的代碼如下所示:
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);
我有一個廣播接收器,它在宣言中定義為:
I have a broadcast receiver that is defined in the manifesto as:
<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"對象即將為空.
My "loc" object is coming up null.
推薦答案
好的,我設(shè)法通過將廣播接收器代碼中的 KEY_LOCATION_CHANGED 更改為:
OK, I managed to fix it by changing the KEY_LOCATION_CHANGED in the broadcast receiver code to:
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();
}
}
這篇關(guān)于Android:使用 LocationManager.requestLocationUpdates() 時如何從 Intent 捆綁包中獲取位置信息的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!