我正在尝试使用Android的LocationManager requestLocationUpdates.一切正常,直到我尝试提取广播接收器中的实际位置对象.我是否需要专门为我的自定义意图定义"额外内容",以便在我将其传递给requestLocationUpdates之前安装Android LocationManager,以便知道如何将其添加到intent中,或者它是否会创建extras-bundle,无论它何时通过触发意图广播接收器?
我的代码看起来像这样:
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);
Run Code Online (Sandbox Code Playgroud)
我有一个广播接收器,在宣言中定义为:
<receiver android:name=".LocationReceiver">
<intent-filter>
<action android:name="com.myapp.swarm.LOCATION_READY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
广播接收机类如下:
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();
}
} …Run Code Online (Sandbox Code Playgroud)