it is very simple code to use broadcast between Activity and IntentService. The MainActivity starts SyncService (which is an IntentService), the SyncService broadcasts messages and MainActivity should receive the messages from SyncService (by using BroadcastReceiver).
but it is strange that the MainActivity cannot get any message from SyncService. Somehow if I call LocalBroadcastManager to broadcast message directly in MainActivity (onCreate() method), the receiver can get the message.
is it because of the different context to initialize LocalBroadcastManager? or there is any other problem?
thanks!
Relavant code in 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);
}
};
Relevant code in 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;
}
Relavent code in 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);
}
Remove addCategory()
from broadcastIntentWithState()
. That is not normally used with any sort of broadcasts (system or local), and your IntentFilter
is not filtering on category.
来源:https://stackoverflow.com/questions/27650832/cannot-receive-broadcast-in-activity-from-localbroadcastmanager-in-intentservice