public class RegisterIntentService extends JobIntentService {
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, RegisterIntentService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Timber.d("onHandleIntent");
String token = null;
InstanceID id = InstanceID.getInstance(this);
Registrar registrar = RegistrarFactory.create();
try {
token = id.getToken(registrar.getSenderId(), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Timber.d("received token");
} catch (Exception e) {
Timber.e(e, "unable to handle intent");
}
Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
if (token != null) registrationComplete.putExtra(Preferences.REGISTRATION_ID, token);
this.sendBroadcast(registrationComplete);
}
}
在清单文件中:
<service
android:name="com.tesco.pushnotification.RegisterIntentService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false" />
在APP处于后台时发送推送通知时,出现以下异常。
> Process: com.tesco.clubcardmobile, PID: 8326
> java.lang.RuntimeException: Unable to start receiver com.google.android.gms.gcm.GcmReceiver:
> java.lang.IllegalStateException: Not allowed to start service Intent {
> act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010
> pkg=com.tesco.clubcardmobile
> cmp=com.tesco.clubcardmobile/com.tesco.pushnotification.GCMListener_Service
> (has extras) }: app is in background uid UidRecord{f0a6ce6 u0a2340
> RCVR idle procs:1 seq(0,0,0)}
使用给定的代码,当APP在Foreground中但不在Notification Manager中时,我能够获得Push Notification。我已经在Android Oreo之前更改了Android Oreo的代码,但是我能够在后台获取通知,但是我不知道为什么我没有得到通知。更改API 26后,当应用程序在后台运行时,我已经将IntentService更改为JOBIntentservice,请告诉我什么我做错了,在出现错误时建议我做什么。