GCM 2.0 在 Android P 中不工作

GCM 2.0 is not working in Android P

我正在 Android P.
中实施 GCM 但是收不到GCM的广播
Android P 有什么问题?
顺便说一下,在 Android O 工作得很好。

    Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    registrationIntent.setPackage("com.google.android.gsf");
    registrationIntent.putExtra("sender", sender_id);
    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));

public class GCMBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String messageType = gcm.getMessageType(intent);

        Log.e("GCM", "action=" + intent.getAction() + " registration_id="+intent.getStringExtra("registration_id"));
    }
}

您使用的 GCM 一定是旧版本。

升级到 GCM 11 或更高版本。 (最新的是15.0.1: com.google.android.gms:play-services-gcm:15.0.1),或者更好,迁移到FCM。 (GCM 现已弃用)

documentation 状态...

As of April 10, 2018, Google has deprecated GCM. The GCM server and client APIs are deprecated and will be removed as soon as April 11, 2019. Migrate GCM apps to Firebase Cloud Messaging (FCM), which inherits the reliable and scalable GCM infrastructure, plus many new features. See the migration guide to learn more.

因此,您可能(迟早)必须迁移到 FCM

最近还有 Firebase In-App Messaging.

我自己使用 GCM 3.0 方法解决了这个问题,如下所示:

public void getInstanceIdToken() {
    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

public class RegistrationIntentService extends IntentService {
    private static String TAG = RegistrationIntentService.class.getSimpleName();

    public RegistrationIntentService() {
        super(TAG);
    }

    String senderId = "YourSenderId";

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        InstanceID instanceID = InstanceID.getInstance(this);
        try {
            String token = instanceID.getToken(senderId,
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}