androidstudio 服务无法在 Androidx 中运行

androidstudio service not Working in Androidx

Activity代码

JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName = new ComponentName(this, EJobService.class);
        JobInfo info = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setPersisted(true)
                .setPeriodic(5*1000,500)
                .build();

        int resultCode = scheduler.schedule(info);
        if (resultCode == JobScheduler.RESULT_SUCCESS) {
            Log.d("Job Started", "Job scheduled");
        } else {
            Log.d("Tag", "Job scheduling failed");
        }

服务代码

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class EJobService extends JobService {
    private static final String TAG = "EJobService";
    private boolean jobCancelled = false;

    @Override
    public boolean onStartJob(JobParameters params) {
       getLocation();
        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    Log.d(TAG, "run: " + i);
                    if (jobCancelled) {
                        return;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                Log.d(TAG, "Job finished");
                jobFinished(params, false);
            }
        }).start();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "Job cancelled before completion");
        jobCancelled = true;
        return true;
    }
   public void getLocation() {
    LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

AndroidManifest.Xml

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

我正在将此代码用于作业调度程序服务,但问题是服务不是 运行 请告诉我问题出在哪里。我已经在 Oreo 版本中使用过它并且工作正常所以请告诉我问题是什么。

获取位置();应用程序崩溃

您的代码运行良好,只需去检查控制台中的输出即可。