在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);
}
答案 0 :(得分:1)
从addCategory()
移除broadcastIntentWithState()
。这通常不适用于任何类型的广播(系统或本地),而您的IntentFilter
不会过滤类别。