How to enable and disable GCM in android?

2019-05-23 08:06发布

问题:

I am using GCM for push notifications in my application. I have a screen where the user has the facility to enable or disable notifications.
Can anyone please tell me how to enable and disable GCM programmatically.

I had seen the below code from this post Android GCM Enable/Disable but it is not clear about the receiver.

PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);

Thanks in advance.

回答1:

If you are referring to the Android setting (adding in Android 4.1 if I remember correctly) that allows a user to enable/disable notifications for an application, I don't think you can change that programmatically.

If, however, you are referring to a settings screen within your own app, you can disable the notifications by un-registering from GCM (GoogleCloudMessaging.unregister). This should stop messages from arriving to your app on that device until you register to GCM again.

Or, if you want your app to keep receiving the messages but stop showing them to the user, you can store a flag in shared preferences which indicates if GCM is enabled. Then the code that handles incoming GCM messages will check this flag to decide what to do with the message.



回答2:

As per Google unregister() method was deprecated.

Instead use InstanceID.deleteToken() or InstanceID.deleteInstanceID().