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

大兔子大兔子 提交于 2019-12-04 21:09:40

问题


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.


回答1:


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 {
...
}


来源:https://stackoverflow.com/questions/8570823/how-to-send-data-to-a-running-activity-from-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!