BroadcastReceiver when app is in background

给你一囗甜甜゛ 提交于 2021-01-28 04:46:42

问题


i am trying to write an app where i do changes to the UI depending on the msgs i send with gcm push notifications and i manged to do so by using BroadcastReceiver onReceive function to implement it but it only work if the app is in foreground but if it was in background or closed nothing happen so any way around that?

edit1: in the manifest file if i understood ur question right

<receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="info.androidhive.gcm" />
            </intent-filter>
        </receiver>

        <service
            android:name="info.droiders.gcm.gcm.MyGcmPushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <service
            android:name="info.droiders.gcm.gcm.GcmIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>

   myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                // notification received
                handleChanges(intent);
            }
        }
    };

回答1:


If you are declaring your broadcast reciever as an member of your activity or other class inside your app, then it won't run unless your app is running. Instead, you should create a stand-alone class that extends Broadcast receiver. So change this:

   myBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
};

to this and place it in its own file:

public class GcmReceiver extends BroadcastReceiver {
     public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
            // notification received
            handleChanges(intent);
        }
    }
}

Now Android can find the class and instantiate it even when your app isn't running.

EDIT: Corrected class name to match the receiver name declared in the manifest file shown in OP.



来源:https://stackoverflow.com/questions/35492582/broadcastreceiver-when-app-is-in-background

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