如何检查 JobService 是否在 Android 中运行?
2022-09-03 17:48:50
我正在我的项目中使用工作服务。它工作得很好。但有时服务会停止。它不会再次重新启动。因此,我正在尝试在未运行的情况下对作业服务进行分层。但我不知道如何检查作业服务是否已经在运行。请让我知道如何检查作业服务是否正在运行。
我的工作服务类:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobService extends android.app.job.JobService {
@Override
public boolean onStartJob(JobParameters params) {
if (NetworkHandler.getInstance().isNetworkAvailable()) {
TaskHandler.getInstance().getTaskListFromServer(PreferenceManagerForPlannedRoute.getInstance().getLastSyncTime(), PreferenceManagerForPlannedRoute.getInstance().getInProgressMoveTask());
NotificationUtils.getInstance().CreateNotification();
Logger.d("Scheduler", "Working!!");
} else {
Logger.d("Network", "not available");
}
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
Logger.d("onStopJob", "Stopped");
return true;
}
}
我的 Util 类:
public class JobSchedulerUtils {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, JobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setRequiresDeviceIdle(false);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPeriodic(5000);
builder.setPersisted(true);
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
}
}
要开始:
synchronized public void startAlarmManager() {
if(Build.VERSION.SDK_INT>=21) {
JobSchedulerUtils.scheduleJob(Application.getInstance().getApplicationContext());
}else {
Intent myIntent = new Intent(Application.getInstance(), AlarmManagerForPlannedRoute.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Application.getInstance(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) Application.getInstance().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), Constants.TIME_DELAY_FOR_TASK_LIST_SERVICE_CALL_IN_SECONDS * 1000, pendingIntent);
}
}
要停止:
synchronized private void stopAlarmManager(Activity activity) {
if(Build.VERSION.SDK_INT>=21){
JobScheduler jobScheduler = (JobScheduler) Application.getInstance().getApplicationContext().getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancelAll();
}else {
Intent myIntent = new Intent(activity, AlarmManagerForPlannedRoute.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}