[英]Cannot receive broadcast in Activity from LocalBroadcastManager in IntentService
在Activity和IntentService之间使用广播是非常简单的代码。 MainActivity启动SyncService(这是一个IntentService),SyncService广播消息,MainActivity应该从SyncService接收消息(通过使用BroadcastReceiver)。
但是奇怪的是MainActivity无法从SyncService获取任何消息。 如果我以某种方式调用LocalBroadcastManager来直接在MainActivity中广播消息(onCreate()方法),则接收者可以获得消息。
是因为上下文不同而初始化LocalBroadcastManager吗? 还是还有其他问题?
谢谢!
MainActivity中的相关代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter statusIntentFilter = new IntentFilter(AppConstants.BROADCAST_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
statusIntentFilter);
final Intent intent = new Intent(this, SyncService.class);
this.startService(intent);
this.sendMessage();
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
SyncService中的相关代码:
public class SyncService extends IntentService {
private static final String TAG = "SyncService";
public SyncService() {
super("SyncService");
mBroadcaster = new BroadcastNotifier(this);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "Handle intent");
mBroadcaster.broadcastIntentWithState(AppConstants.STATE_ACTION_STARTED);
mBroadcaster.broadcastIntentWithState(AppConstants.STATE_ACTION_COMPLETE);
Log.d(TAG, "Finish intent");
}
private BroadcastNotifier mBroadcaster;
}
BroadcastNotifier中的相关代码:
private LocalBroadcastManager mBroadcaster;
public BroadcastNotifier(Context context) {
// Gets an instance of the support library local broadcastmanager
Log.d(TAG, "Start to create broadcast instance with context: " + context);
mBroadcaster = LocalBroadcastManager.getInstance(context);
}
public void broadcastIntentWithState(int status) {
Intent localIntent = new Intent(AppConstants.BROADCAST_ACTION);
// The Intent contains the custom broadcast action for this app
//localIntent.setAction();
// Puts the status into the Intent
localIntent.putExtra(AppConstants.EXTENDED_DATA_STATUS, status);
localIntent.addCategory(Intent.CATEGORY_DEFAULT);
// Broadcasts the Intent
mBroadcaster.sendBroadcast(localIntent);
}
从addCategory()
删除addCategory()
broadcastIntentWithState()
。 通常,这不适用于任何类型的广播(系统广播或本地广播),并且IntentFilter
不会按类别进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.