Adam
Adam

Reputation: 1982

Android Broadcast from Service To Activity

I am trying to send a Broadcast from a service out to an Activity. I can verify the broadcast is sent from within the service, but the Activity doesn't pick up anything.

Here is the relevant service code:

   Intent i = new Intent(NEW_MESSAGE);  
   i.putExtra(FriendInfo.USERNAME, StringUtils.parseBareAddress(message.getFrom()));
   i.putExtra(FriendInfo.MESSAGE, message.getBody());
   i.putExtra("who", "1");
   sendBroadcast(i);

And the receiving end in the activity class:

public class newMessage extends BroadcastReceiver 
{
@Override
   public void onReceive(Context context, Intent intent) 
   {    
    String action = intent.getAction();
       if(action.equalsIgnoreCase(IMService.NEW_MESSAGE)){    
          Bundle extra = intent.getExtras();
          String username = extra.getString(FriendInfo.USERNAME);   
          String message = extra.getString(FriendInfo.MESSAGE);
          String who = extra.getString("who");
         }
   }
}

The BroadcastReceiver is defined within an Activity. I am registering the receiver in the onCreate method of the Activity, not in the Manifest file.

I'm stumped as to why it won't rec. anything.

Any insight?

EDIT
Registering takes place as follows:

 registerReceiver(messageReceiver, new IntentFilter(IMService.NEW_MESSAGE));

Where "messageReceiver" is defined as

private newMessage messageReceiver = new newMessage();

IMService.NEW_MESSAGE is merely a string = "NewMessage"

Upvotes: 16

Views: 23927

Answers (3)

Adam
Adam

Reputation: 1982

I'm not sure if it is specific to the set up, or if it is a fix in general, but moving the register/unregister to the onResume/onPause _respectively_ and not registering in the onCreate solved the problem for me.

Upvotes: 10

Tushar Bapte
Tushar Bapte

Reputation: 151

Inner class broadcast receiver will not be able to handle broadcast(means it unable to locate that class ). So make it as a separate class

Definitely it will work.

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

Try this two things:

  1. Use manifest file to register receiver(but it barely helps)
  2. Try make your Receiver a regular class, not inner one.

Upvotes: 1

Related Questions