Not receiving GCM notifications with app in backgr

2019-09-08 18:37发布

问题:

I developing an Ionic 2 app and testing on Android emulator.

When the app is in background and the notification has no title, no message and content-available=1 the notification should be sent directly to app notification handler. But its not happening.

I can receive notifications with the app in foreground.

If I have a title and a message I receive the notification in the notification area. But I need to send the notification directly to the app in silent mode, without pass by the notification area.

Here is my code to send push notifications:

{
   "delay_while_idle": true,
   "priority": "high",
   "sound": "default",
   "color": "FFFF00",
   //payload   
   "data": {
       "content-available": "1",
       "some_var": "some_value",
       "ohter_var": "other_value",       
   }
}

How could I sent silent notifications to my Android app?

回答1:

Android GCM and FCM both also work when app background.

For that you need to add below service classes at manifest with intent Filter.

<!-- [START gcm_listener] -->
        <service
            android:name=".gcm.GcmListener"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name=".gcm.TokenRefreshService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
        <service
            android:name=".gcm.RegistrationIntentService"
            android:exported="false" />
        <!-- [END gcm_listener] -->


public class GcmListener extends GcmListenerService {
}


public class TokenRefreshService extends InstanceIDListenerService {
    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

To get token:

public class RegistrationIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    private String TAG = "RegistrationIntentService";

    public RegistrationIntentService() {
        super("RegistrationIntentService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
     InstanceID instanceID = InstanceID.getInstance(this);
        String token = instanceID.getToken("PRODUCT_ID",
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
}
}