当前位置: 首页 > 面试题库 >

不允许启动服务意图-Android Oreo

朱昊乾
2023-03-14
问题内容

我目前正在使用在Oreo中崩溃的startWakefulService函数。我意识到我要么必须切换到startForegroundService()并使用前台服务,要么切换到JobIntentService,但是基于下面的代码,我不确定该怎么做。(对不起,我是android新手)。正确方向的任何观点将不胜感激。

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    // Explicitly specify that GCMIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));

    setResultCode(Activity.RESULT_OK);
}
}

这是在Android 8.x上运行时遇到的当前错误

致命异常:java.lang.RuntimeException无法启动接收器com.heyjude.heyjudeapp.gcm.GcmBroadcastReceiver:java.lang.IllegalStateException:不允许启动服务意图{act
= com.google.android.c2dm.intent.RECEIVE flg = 0x1000010 pkg = com.app.app
cmp = com.app.app / .gcm.GCMIntentService(有其他功能)}:应用程序位于后台uid UidRecord



问题答案:

我也有同样的行为。

为什么会发生此问题?

由于Android 8
具有新的后台执行限制,因此您不应启动服务后台。

我如何解决

将您的迁移GCMIntetService到,JobIntentService而不是IntentService

请按照以下步骤操作:1)将BIND_JOB_SERVICE权限添加到您的服务中:

<service android:name=".service.GCMIntentService"
        android:exported="false"
        android:permission="android.permission.BIND_JOB_SERVICE"/>

2)在您的内部GCMIntentService(而不是扩展)IntentService,使用android.support.v4.app.JobIntentService并覆盖onHandleWork,然后删除其中overrideonHandleIntent

public class GCMIntentService extends JobIntentService {

    // Service unique ID
    static final int SERVICE_JOB_ID = 50;

    // Enqueuing work in to this service.
    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, GCMIntentService.class, SERVICE_JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        onHandleIntent(intent);
    }

    private void onHandleIntent(Intent intent) {
        //Handling of notification goes here
    }
}

最后,在您的GCMBroadcastReceiver队列中GCMIntentService

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        // startWakefulService(context, (intent.setComponent(comp)));

        //setResultCode(Activity.RESULT_OK);

        GCMIntentService.enqueueWork(context, (intent.setComponent(comp)));
    }
}

在我们将目标sdk更新为27之后,此实施对我来说很有效,希望它对您有用。



 类似资料: