首页 > 解决方案 > Android 8.0 - Job Intent Service 在启动时不运行应用程序

问题描述

最初我有 Android 7.0 并且使用和服务没有任何问题BroadcastReceiver。但是随着 Android 8.0 的变化。我需要切换到一个JobIntentService,以便我的应用程序可以在启动时运行。

我已经尝试迁移我的代码以匹配JobIntentService但在启动时没有发生任何事情。我不确定原因是因为我的服务等级还是我的BroadcastReceiver等级。

AndroidManifest.xml

    <service android:name=".backgroundService"
                android:permission="android.permission.BIND_JOB_SERVICE"/>

背景服务.java

    public class backgroundService extends JobIntentService {

        public static final int JOB_ID = 0x01;

        public static void enqueueWork(Context context, Intent work) {
            enqueueWork(context, backgroundService.class, JOB_ID, work);
        }


        @Override
        protected void onHandleWork(@NonNull Intent intent) {

            Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show();
            Intent dialogIntent = new Intent(this, Home.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
        }
    }

启动启动.java

    public class startOnBoot extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Log.i("In" , "getAction() - Boot");
                backgroundService.enqueueWork(context, intent);
            }
            else
                Log.i("No" , "Boot");
        }
    }

所以我试图从本质上开始Home.class启动。

标签: javaandroidbroadcastreceiverjobintentservice

解决方案


我试了一下,它可以正常运行。您可以查看以下三个提示。

1.检查您是否已声明RECEIVE_BOOT_COMPLETED许可。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2.检查你是否已经用BOOT_COMPLETEDaction声明了receiver。

<receiver android:name=".startOnBoot">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

3.Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show();在您的服务中删除或在主线程中烘烤它。否则它会给你错误java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()


推荐阅读