это очень простой код для использования трансляции между 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);
}