LocationPoller和多个广播接收器

时间:2012-04-10 14:25:06

标签: java android broadcastreceiver commonsware-cwac

我正在使用cwac-Location Poller(来自here)来不断轮询用户位置并显示基于位置的通知。这一切都运行良好,但现在我正在尝试附加另一个BroadcastReceiver,以便如果我的应用程序在前台,而不是显示通知动画谷歌地图到当前用户位置。但出于某种原因,我无法让它发挥作用。

onCreate()的{​​{1}}方法我有以下代码来启动poller:

MapActivity

@Override public void onCreate(Bundle savedInstanceState) { ..... alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent i = new Intent(this, LocationPoller.class); Bundle bundle = new Bundle(); LocationPollerParameter parameter = new LocationPollerParameter(bundle); parameter.setIntentToBroadcastOnCompletion(new Intent(this, LocationReceiver.class)); parameter.setProviders(new String[] {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER}); parameter.setTimeout(60000); i.putExtras(bundle); pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pendingIntent); } 方法中我使用onResume()方法注册另一个接收方:

registerReceiver()

locationReceiver的位置如下:

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter(com.commonsware.cwac.locpoll.LocationPollerParameter.INTENT_TO_BROADCAST_ON_COMPLETION_KEY);
    intentFilter.setPriority(1);
    registerReceiver(locationReceiver, intentFilter);
}

为了向多个接收者发送有序广播,我修改了private BroadcastReceiver locationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "mapActivity called"); abortBroadcast(); } }; 以使用LocationPollerService代替sendOrderedBroadcast

sendBroadcast

现在的问题是我的动态注册接收器永远不会被调用,但AndroidManifest.xml中提到的接收器会:

public void onLocationChanged(Location location) {
      handler.removeCallbacks(onTimeout);
      Intent toBroadcast = createIntentToBroadcastOnCompletion();

      toBroadcast.putExtra(LocationPollerResult.LOCATION_KEY, location);        
      sendOrderedBroadcast(toBroadcast, null);
      quit();
}

1 个答案:

答案 0 :(得分:2)

您的问题是您在Java中创建的IntentFiltercreateIntentToBroadcastOnCompletion()实施之间的断开连接,您未在问题中包含这些内容。您的IntentFilter期待带有特定操作字符串的广播 - 您在Intent中创建的createIntentToBroadcastOnCompletion()显然不包含此操作字符串。

BTW,关于“并且为了向多个接收器发送广播”,sendBroadcast()完全能够向多个接收器发送广播。