gpt4 book ai didi

androidstudio 服务无法在 Androidx 中运行

转载 作者:行者123 更新时间:2023-11-29 00:52:21 27 4
gpt4 key购买 nike

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 版本中使用了它并且工作正常所以请告诉我问题是什么。

获取位置();崩溃应用

最佳答案

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

关于androidstudio 服务无法在 Androidx 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58131314/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com