我尝试通过将 PendingIntent 传递给 locationClient 来检索位置,但我在广播接收器中收到的 Intent 中没有位置。
这是我的代码:
开始位置请求
@Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
notifyIntent = new Intent(RunActivity.this, RunActivity.AlarmReciever.class);
notifySender = PendingIntent
.getBroadcast(RunActivity.this, 899899, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notifyIntent.setAction("com.blabla.blabla.NOTIFY_GPS");
locationClient.requestLocationUpdates(locationRequest, notifySender);
}
接收者
<receiver android:name=".RunActivity$AlarmReciever"
android:exported="true">
<intent-filter>
<action android:name="com.blabla.blabla.NOTIFY_GPS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
广播接收器
public static class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("RECIEVED LOCATION UPDATE", "INTENT");
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
Log.d("LOCATION", null == loc ? "emptyloc" : loc.toString());
}
}
这将始终打印“LOCATION:emptyloc”。
有什么想法吗?
P.S.:忘记提及位置工作正常,如果我调用 locationClient.getLastLocation()
我将按预期检索位置。仅当 PendingIntent 时,location 才为 null;
最诚挚的问候。
最佳答案
我的错,位置不为空,我的 key 错误。
我通过获取所有 bundle key 并迭代它们解决了这个问题:
for (String key : b.keySet()) {
try {
Log.d("bundle object", b.get(key).toString());
} catch (Exception e) {
e.printStackTrace();
}
}
关于java - 获取带有挂起 Intent 的位置更新会返回空位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616388/