AndroidStudio Service 無法在 Androidx 中運作



活动代码

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" />

我正在将此代码用于作业调度程序服务,但问题是服务未运行,请告诉我问题是什么。 我已经在奥利奥版本中使用了它,这工作正常,所以请告诉我有什么问题。

Getlocation((; 使应用程序崩溃

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

相关内容

  • 没有找到相关文章

最新更新