Activity と IntentService の間でブロードキャストを使用するのは非常に単純なコードです。MainActivity は SyncService (IntentService) を開始し、SyncService はメッセージをブロードキャストし、MainActivity は (BroadcastReceiver を使用して) SyncService からメッセージを受信する必要があります。
しかし、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);
}