我正在使用无限期运行的服务(使用自己的进程)和GcmListenerService的扩展来接收推送消息。推送消息将在服务内启动操作。 问题是,如果应用程序从最近使用的应用程序关闭/删除,该服务仍在运行,但如果收到新消息则会立即停止。进程列表显示首先终止后台进程,然后启动通常的应用程序进程而不处理推送消息。
的AndroidManifest.xml
<application android:allowBackup="false" android:label="@string/app_name"
android:icon="@drawable/icon" android:theme="@style/AppTheme"
android:process="domain.android.Application"
android:name=".Application">
<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="domain.android" />
</intent-filter>
</receiver>
<service
android:name=".service.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".service.BackgroundService"
android:icon="@drawable/icon"
android:label="@string/service_name"
android:process="domain.android.service.BackgroundService"
android:exported="false"
android:enabled="true"/>
</application>
GCM听众
public class MyGcmListenerService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
String code = data.getString("code");
if ("j".equals(code)) {
final String id = data.getString("id", null);
String status = data.getString("status", null);
Intent serviceIntent = new Intent(getBaseContext(), domain.android.service.BackgroundService.class);
serviceIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
serviceIntent.putExtra("method", "push");
serviceIntent.putExtra("id", id);
serviceIntent.putExtra("status", status);
serviceIntent.putExtra("notificationId", (new Date()).getTime());
startService(serviceIntent);
}
}
}
服务:
public class BackgroundService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
if (intent.hasExtra("method")) {
// Start processing
}
}
@Override
public void onCreate() {
Intent notificationIntent = new Intent(this, Main.class);
PendingIntent intent = PendingIntent.getActivity(getBaseContext(), 0, notificationIntent, 0);
android.app.Notification.Builder builder = new android.app.Notification.Builder(this)
.setContentIntent(intent)
.setContentTitle(getText(R.string.app_name))
.setContentText("Connected")
.setSmallIcon(R.drawable.marker_walker_white);
android.app.Notification notification = builder.build();
startForeground(1, notification);
}
}