Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data to a running activity from Broadcast Receiver,

I am able to receive C2DM message fine but I want to send the data to a running activity, i.e when the activity is running, if the receiver receives C2DM message it is to send the data to the running activity. The code of receiver is (no bugs in the code):

public class C2dmreceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.w("C2DM", "Message Receiver called");
        if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) 
        {
            final String payload = intent.getStringExtra("key1");   
            Log.d("C2DM", "message = " + payload );
       }
     }}

I have tried like this inside the activity in an attempt to register the receiver in the activity so that the receiver can send data and the running activity can receive the data :-

C2dmreceiver c2dmr = new C2dmreceiver();
Registration.this.registerReceiver(c2dmr, new IntentFilter());

I don't know what to put inside the IntentFilter(), also what else I have to put in the code of the activity and the code of the receiver so that while the activity is running and some C2DM message comes the receiver can send the data to the running activity.

So, please tell me the code that is to put in the activity and in the receiver and may also be in the manifest so that the data from the receiver could be send to running activity.

Any advice is highly appreciated.

like image 984
VISHAL DAGA Avatar asked Dec 20 '11 04:12

VISHAL DAGA


1 Answers

First of all it's not the best idea to subscribe c2dm receiver in activity. Do it in manifest. For passing data to activity you can create static string field in Activity and set you String there.

You can do something like this:

in Activity

public static YourActivity mThis = null;
@Override
protected void onResume() {
    super.onResume();
    mThis = this;
}
@Override
protected void onPause() {
    super.onPause();
    mThis = null;
}

In your BroadcastReceiver:

@Override
public void onReceive(Context context, Intent intent) {
...
if (YourActivity.mThis != null) {
    ((TextView)YourActivity.mThis.findViewById(R.id.text)).setText("received c2dm");
}
else {
...
}
like image 93
Jin35 Avatar answered Nov 08 '22 15:11

Jin35