这是可选分配的一部分。我有一个Activity动态注册一个广播接收器,并启动一个IntentService。广播接收器应该在执行其工作后从IntentService接收该意图。但是,在IntentService发送广播之后,不会调用onReceive。
我正在记录输出,并且我收到的最后一条日志是IntentService发送广播后的结果。之后,我不知道如何继续调试。
请咨询。
我的代码有什么问题,使得没有调用onReceive()方法?
编辑:答案(来自HeyAlex)
IntentService正在通过LocalBroadcastManager发送广播,而由Activity启动的广播接收器未注册到LocalBroadcastManager实例,而是正常的动态寄存器。因此,广播接收方没有选择发送的广播。
DownloadAtomFeedService(扩展IntentService)
@Override
public void onHandleIntent(Intent intent) {
List<Entry> entries = downloadAtomFeed(uri.toString());
int requestCode = intent.getExtras().getInt(REQUEST_CODE);
sendEntries((ArrayList<Entry>) entries,uri,requestCode);
Log.d(TAG, "onHandleIntent: returning to MainActivity");
}
private void sendEntries(ArrayList<Entry> entries,
Uri url,
int requestCode) {
Bundle bundle = makeReplyBundle(entries,url,requestCode);
Intent intent = new MainActivity().makeBroadcastReceiverIntent();
intent.putExtras(bundle);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
Log.d(TAG, "sendEntries: SENT BROADCAST");
}
private Bundle makeReplyBundle(ArrayList<Entry> entries,
Uri url,
int requestCode) {
Bundle data = new Bundle();
data.putParcelableArrayList(ENTRY_ARRAY_KEY,entries);
data.putInt(REQUEST_CODE,requestCode);
data.putString(FEED_URL,url.toString());
if(entries == null){
data.putInt(DOWNLOAD_RESULTS,Activity.RESULT_CANCELED);
}else data.putInt(DOWNLOAD_RESULTS,Activity.RESULT_OK);
return data;
}
MainActivity
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(DownloadStateReceiver.BROADCAST_ACTION);
DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver();
registerReceiver(mDownloadStateReceiver,intentFilter);
android.util.Log.d(TAG, "onResume: downloadstatereceiver registered");
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mDownloadStateReceiver);
super.onPause();
}
public static Intent makeBroadcastReceiverIntent() {
Intent intent = new Intent().setAction(DownloadStateReceiver.BROADCAST_ACTION);
return intent;
}
public class DownloadStateReceiver extends BroadcastReceiver {
public static final String BROADCAST_ACTION =
"myassignment.activities.BROADCAST";
public DownloadStateReceiver() {
android.util.Log.d(TAG, "DownloadStateReceiver: ");
}
public void onReceive(Context context, Intent intent) {
MainActivity.this.serviceIntentReceived(intent.getExtras());
android.util.Log.d(TAG, "onReceive: BroadcastReceived");
}
}
答案 0 :(得分:1)
问题是您不是通过LocalBroadcastManager注册BroadcastReceiver。只需将您的onResume设置为:
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(DownloadStateReceiver.BROADCAST_ACTION);
mDownloadStateReceiver = new DownloadStateReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver,intentFilter);
android.util.Log.d(TAG, "onResume: downloadstatereceiver registered");
}