Search code examples
androidbroadcastreceiverandroid-service

BroadcastReceiver within a Service not receiving broadcasts Android


I've got this app, in which users update certain variables in an Activity, and this Activity passes the new variables to a IntentService using a BroadcastReceiver. However, the BroadcastReceiver in the IntentService doesn't seem to be receiving the broadcasts. This is the code within the service to create the broadcast receiver

protected class UpdateReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){
        Log.d("receiver", "Got message: ");
        //state=3;
        //Toast.makeText(context, "got it", Toast.LENGTH_SHORT).show();
    }
};

And here's the code to register the receiver, in the onHandle() function

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("updates");
UpdateReceiver lol = new UpdateReceiver();
DetectService.this.registerReceiver(lol, intentFilter);

Finally here's the code to send the broadcast, from the activity

Intent broadcastIntent = new Intent();
broadcastIntent.setAction("updates");
HomePageActivity.this.sendBroadcast(broadcastIntent);
Log.d("sender", "send msg");

When I put the receiver in the same activity as the broadcasting part, it works, but not when I put it into the IntentService. Help please!

On another related note, I've tried using LocalBroadcastManager in this project since the broadcasts are all local but eclipse doesn't seem to be able to import the compatibility class. I've installed it using Android SDK manager already. Is there any thing I'm doing wrong here?


Solution

  • this Activity passes the new variables to a IntentService using a BroadcastReceiver.

    That makes no sense. Use startService() to send a command to an IntentService. And an IntentService should not have a BroadcastReceiver, because the IntentService will be destroyed as soon as onHandleIntent() completes and therefore will never receive the broadcast.

    I've tried using LocalBroadcastManager in this project since the broadcasts are all local but eclipse doesn't seem to be able to import the compatibility class.

    :: shrug ::

    Here is a sample project with Eclipse project files that uses LocalBroadcastManager. I encountered no particular Eclipse issues when creating the project.