无法通过Android Oreo中的JobScheduler启动服务

时间:2018-07-20 04:43:11

标签: android service android-8.0-oreo android-jobscheduler

我创建了一个使用Firebase服务的应用程序。只要值发生变化,就会生成通知。因此,为此,我的服务必须连续运行,否则将没有任何通知。我确实创建了它并成功地使其在pre-oro Android OS中运行。即使从最近的用户清除并强制关闭后,我的服务也运行良好,但在Oreo中却没有。 谷歌搜索后,我知道奥利奥禁止自动启动服务。为此,我们需要JobScheduler。

这是我的JobService类-

public static void outputArray(int[][] array) {
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j< array[i].length; j++){
            for(int k = i; k < array.length; k++){
                for(int l = j; l < array[i].length; l++){
                    System.out.print("["+i+","+j+"]--->"+"["+k+","+l+"]");
                    int sum = 0;
                    for(int x = i; x <= k; x++){
                        for(int y = j; y<= l; y++){
                            sum+=array[x][y];
                        }
                    }
                    System.out.println("--->"+sum);
                }
            }
        }
    }
}

PS-扩展JobService给出了错误,它要求最小api = 21,所以我使用 @RequiresApi(api = Build.VERSION_CODES.O)对其进行了纠正

在我的服务的import android.app.job.JobParameters; import android.app.job.JobService; import android.content.Intent; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; @RequiresApi(api = Build.VERSION_CODES.O) public class Serviceo extends JobService { private JobParameters params; @Override public boolean onStartJob(JobParameters jobParameters) { this.params = jobParameters; Log.d("HEYY","i'm here"); Intent service = new Intent(getApplicationContext(), NotificationService.class); getApplicationContext().startService(service); return true; } @Override public boolean onStopJob(JobParameters jobParameters) { return false; } } 方法中,我这样声明我的JobService-

onDestroy

该方法已执行,但服务尚未启动。我可以在logcat中看到“ hi2”已执行。 我也在清单中声明了它

 @Override
public void onDestroy() {
    super.onDestroy();
    Log.i("EXIT", "ondestroy!");
    Intent broadcastIntent = new Intent("com.mukesh.mu.RestarterBroadcastReceiver");
    sendBroadcast(broadcastIntent);
    stoptimertask();

    Log.i("BRUHHH","hi");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Log.i("BRUHHH","hi2");
        jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

    JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(),
            Serviceo.class.getName()));

    //run job service after every 5 seconds
    builder.setPeriodic(5000);
    jobScheduler.schedule(builder.build());

    }

通过Intent和广播,在Oreo之前的所有版本中一切正常,但在Oreo中不起作用。

1 个答案:

答案 0 :(得分:0)

您可以尝试Job Service的替代方案-Firebase JobDispatcher