gpt4 book ai didi

android - 检查服务是否已经在运行

转载 作者:行者123 更新时间:2023-11-29 16:38:07 24 4
gpt4 key购买 nike

我有一项服务在我的 Android 应用程序的应用程序类中启动。

该服务每小时运行一次,我不希望它在每次打开应用程序时都启动,这似乎是它现在所做的。我想检查它是否正在运行,如果没有,则运行它。

I found this code在另一个我认为可行的答案中,但如果我运行该应用程序两次,我仍然会从以下代码中收到消息“服务未运行,计划作业”:

public class App extends Application {

public static final String TAG = "Application";
public static final int JOB_NUMBER = 3007;

@Override
public void onCreate() {
super.onCreate();
if(!isMyServiceRunning(DevotionalService.class)) {
ComponentName componentName = new ComponentName(this, DevotionalService.class);
JobInfo info = new JobInfo.Builder(JOB_NUMBER, componentName)
.setRequiresCharging(false)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.setPeriodic(60 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Service is not running, Job Scheduled.");
} else {
Log.d(TAG, "Service is not running, However job scheduling failed.");
}
} else {
Log.d(TAG, "Service is already running.");
}
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

public void cancelJob() {
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(JOB_NUMBER);
Log.d(TAG, "Job Cancelled.");
}
}

有人知道为什么会这样吗?

最佳答案

检查服务是否正在运行:

class MyService extends Service {
private static boolean isRunning;
public int onStartCommand (Intent intent,
int flags,
int startId) {
isRunning = true;
...
}
public void onDestroy() {
isRunning = false;
}
public static boolean isRunning() {
return isRunning;
}
}

然后检查它是否正在运行,只需检查 MyService.isRunning()

检查服务是否已安排:

if(JobScheduler.getPendingJob(jobID) == null) {
//job notscheduled
}

关于android - 检查服务是否已经在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053583/

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