每当应用在Android Pie中被杀死时,服务也会被杀死

时间:2019-07-08 01:34:43

标签: java android android-9.0-pie jobintentservice

我正在通过创建一个android应用程序来学习Android编程。但是每当我杀死应用程序服务时也会被杀死。我正在使用JobIntentService。使该应用程序在后台运行。

JobIntentService类

public class BackGroundDistanceCalculate extends JobIntentService {

    final public static String TAG = "BackGroundDistance";

    static void enqueueWork(Context context, Intent job) {
        enqueueWork(context, BackGroundDistanceCalculate.class, 1, job);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Start");
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Log.d(TAG, "Execution Started");

        int i=0;

        for(i=0; i<1000; i++) {
            SystemClock.sleep(1000);
        }
    }

    @Override
    public boolean onStopCurrentWork() {
        Log.d(TAG,"Now It's Stopped");
        return super.onStopCurrentWork();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"Now It's Destroyed");
        super.onDestroy();
    }
}

MainActivity

Intent backCheck = new Intent(MapsActivity.this, BackGroundDistanceCalculate.class);
BackGroundDistanceCalculate.enqueueWork(this, backCheck);

创建了在Activity中启动onCreateMethod的意图

清单

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service
    android:name=".BackGroundDistanceCalculate"
    android:permission="android.permission.BIND_JOB_SERVICE" />

即使应用程序被终止,我可以进行哪些更改以使服务成功运行?预先感谢。

2 个答案:

答案 0 :(得分:0)

使用不可撤销的通知启动前台服务

答案 1 :(得分:0)

好吧,您需要将服务迁移到前台服务或至少显示正在进行的通知,因为从android 8.0开始,应用程序无法在不让用户知道的情况下运行后台服务。仍然,如果要在没有通知的情况下,一种方法是迁移您对无障碍服务Create accessibility service 的服务。 如果要创建一个链接,可以参考此链接。

相关问题