简体   繁体   中英

Broadcasting intent from BroadcastReceiver to Activity

I have registered a BroadcastReceiver in manifest:

<receiver android:name=".OrderReceiver" android:permission="com.google.android.c2dm.permission.SEND" android:exported="true">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.gndp" />
</intent-filter>
</receiver>

and in OrderReceiver class I'm trying to broadcast a received intent this way:

public class OrderReceiver extends BroadcastReceiver {

    public void onReceive(Context mContext, Intent intent) {
                 if(intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
                 intent.setAction("com.gndp.device.REGISTERED");
                 mContext.sendBroadcast(intent); //BAZINGA
             }

}

This broadcasted intent(BAZINGA) is received in this class(OrderReceiver) but not in another activity where i want to receive it. Here's the activity:

public class RegisterActivity extends Activity {
    private BroadcastReceiver deviceRegisteredBroadcastReciever;
    @Override
    onCreate(){
        ...
        deviceRegisteredBroadcastReciever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                             //broadcast never reach here<----PROBLEM
                             }
    }

    @Override
    onResume() {
        ...
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);
        lbm.registerReceiver(deviceRegisteredBroadcastReciever, new IntentFilter("com.gndp.device.REGISTERED"));
    }

}

Have tried a lot of things including sending broadcast by instance of LocalBroadcastManager, using an inner class instead of BroadcastReceiver in the activity.

RegisterActivity is in foreground when OrderReceiver receives its first broadcast and it stays in foreground.

You send a global broadcast in the OrderReceiver by calling sendBroadcast of Context class and trying to receive this with LocalBroadcastManager .

You should either broadcast with LocalBroadcastManager or register ordinary BroadcastReceiver with Activity.registerReceiver method in the RegisterActivity .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM