问题
I have a problem sometimes with my GCM service which is closed when RAM of my smartphone is automatically cleared (read this if you need more details).
As far as I understand if I set my service to run in foreground it should help the system to to delete it with RAM. The method of Service.class
onStartCommand()
is usually used to run startForeground()
method.
But with the latest version of GCM implementation it is impossible since the onStartCommand()
method of the parent GCMListenerService.class
is defined as final and I cannot override it.
So how can I set my gcm receiver to rum in foreground?
Here is my manifest part about GCM.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.app.path" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- ... other permissions -->
<permission
android:name="my.app.path.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="my.app.path.permission.C2D_MESSAGE" />
<application
...>
<!-- ... activites... -->
<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="my.app.path" />
</intent-filter>
</receiver>
<service
android:name=".MyGcmListener"
android:exported="false"
android:enabled="true" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
</application>
</manifest>
Thank you in advance.
回答1:
This question is quite old but I think it's worth to answer for the benefit os the future readers.
With GCM (or the new FCM) there is NO NEED to keep GCMListenerService in foreground.
Indeed there is no need to keep the app running at all.
When a GCM message is received by the system, your app will be started and the relevant service (GCMListenerService in GCM or FirebaseMessagingService in FCM) will be executed.
The real issue raised by this post is:
GCM messages are not arriving when the application is not running.
This is due to a special feature of xiaomi that blocks GCM messages.
see: Autostart whitelist inside the Security section.
http://en.miui.com/thread-117992-1-1.html
来源:https://stackoverflow.com/questions/33627053/how-to-run-gcmlistenerservice-in-foreground