From the examples, it looked simple. Maybe you can show me what I did wrong. I cannot get activity to receive broadcast sent from local service.
I have an Activity1 that starts Service1:
startService(new Intent(Activity1.this, Service1.class));
Action1 then starts Activity2:
startActivity(new Intent(Activity1.this, Activity2.class));
Service1, the local service, listens for downloads:
protected final BroadcastReceiver service2DownloadBroadcastReceiver = new BroadcastReceiver() { public void onReceive(final Context context, final Intent intent) { ... broadcastDownloadFinished(Uri.fromFile(downloadedFile));
Then the broadcast receiver Service1 transmits its message:
protected Intent broadcastDownloadFinished(final Uri uri) { final Intent intent = new Intent(ACTION_DOWNLOAD_FINISHED).setData(checkNotNull(uri)); sendBroadcast(intent);
Activity2, which is in the foreground at the time, listens for the ACTION_DOWNLOAD_FINISHED intent using its own broadcast receiver:
private final BroadcastReceiver activity2DownloadBroadcastReceiver = new BroadcastReceiver() { public void onReceive(final Context context, final Intent intent) { Log.i(Activity2.class.getSimpleName(), "Received download event: " + intent.getAction() + " " + intent.getData());
Activity2, of course, registers the recipient:
protected void onResume() { super.onResume(); final IntentFilter downloadIntentFilter = new IntentFilter(); downloadIntentFilter.addAction(ACTION_DOWNLOAD_FINISHED); registerReceiver(activity2DownloadBroadcastReceiver, downloadIntentFilter);
In case it matters, ACTION_DOWNLOAD_FINISHED is something like "com.example.intent.action.DOWNLOAD_FINISHED" .
Service1 receives the boot manager event at its receiver and apparently broadcasts its own custom event, but Activity2 never receives it. What have I done wrong? Is it a problem of translating intent in the middle of processing another? (I wouldn’t think so - it is asynchronous, right?)
Update. To make sure that there is no problem sending the broadcast in the middle of receiving the broadcast, I changed my broadcast code to actually complete the broadcast after three seconds in the main stream:
Log.i(getClass().getSimpleName(), "...ready to broadcast"); final Intent intent = new Intent(ACTION_DOWNLOAD_FINISHED).setData(checkNotNull(uri)); mainThreadHandler.postDelayed(new Runnable() { public void run() { Log.i(getClass().getSimpleName(), "...broadcasting"); sendBroadcast(intent); Log.i(getClass().getSimpleName(), "...broadcasted"); } }, 3000); Log.i(getClass().getSimpleName(), "...scheduled to broadcast");
As expected, the magazine says:
...ready to broadcast ...scheduled to broadcast ...broadcasting ...broadcasted
However, nothing was received in the activity. Please, help.