且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android中启用和禁用GCM?

更新时间:2022-10-29 19:19:40

如果您指的是Android设置(如果我没有记错的话,在Android 4.1中添加)允许用户为应用程序启用/禁用通知,但我认为您不能以编程方式更改该设置。

但是,如果您在自己的应用程序中引用设置屏幕,则可以通过从GCM中取消注册来禁用通知( GoogleCloudMessaging .unregister )。这应该会阻止邮件到达该设备上的应用程序,直到您再次注册到GCM。



或者,如果您希望应用继续收到邮件但不再显示邮件对用户而言,您可以在共享首选项中存储标志,指示是否启用GCM。然后,处理传入的GCM消息的代码将检查该标志以决定如何处理该消息。


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.

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.