[英]Android, Work manager starts service after ~2-3 minutes after killing my app
我正在使用工作管理器来运行我的服务(前台服务),即使该应用程序被杀死之后也是如此。 但是,当我杀死我的应用程序后,我的服务会在杀死我的应用程序2至3分钟后启动。 终止应用程序后,如何使工作管理员立即启动我的服务?
我正在为工作管理器使用以下代码:
public class DemoSyncJob extends Worker {
public static final String TAG = ">>>> job_demo_tag";
public DemoSyncJob(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
@NonNull
public Worker.Result doWork() {
// run your job here
Log.d(TAG, "onRunJob: ");
if(!isMyServiceRunning(getApplicationContext(), MessageReceiverService.class)){
Intent intent=new Intent(getApplicationContext(),MessageReceiverService.class);
getApplicationContext().startService(intent);
}
scheduleJob();
return Worker.Result.success();
}
public static WorkRequest scheduleJob() {
return new OneTimeWorkRequest.Builder(DemoSyncJob.class)
.build();
}
public static boolean isMyServiceRunning(Context context, Class<?> serviceClass) {
try {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
}catch (Exception e){
Log.e(TAG, "isMyServiceRunning: ",e );
}
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.