我有一个必须一直运行的粘性后台服务。基本上它跟踪时间,它是一个自定义时钟计时器。但是一旦设备进入空闲状态(当手机屏幕关闭时),计时器(后台服务)也会暂停。
如何让它即使在屏幕关闭时也始终保持运行?
public class TimerService extends Service {
private Context context;
@Override
public IBinder onBind(Intent intent) {
Logger.LogI(TAG, "Service binding");
return null;
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
最佳答案
所以当设备进入休眠模式时,有一些方法可以使服务不被终止。 我将我的服务作为通知附带的前台服务启动。我并不是说这是长期服务的更好方法。但是当然这个解决方案是开放的,可以进行更多优化。此解决方案不会让服务在 sleep 模式下进入暂停状态。
以下是整个服务代码:
public class TimerService extends Service {
private ScheduledExecutorService scheduleTaskExecutor;
private Context context;
@Override
public IBinder onBind(Intent intent) {
Logger.LogI(TAG, "Service binding");
return null;
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
setNotification();
if (scheduleTaskExecutor == null) {
scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new mainTask(), 0, 1, TimeUnit.SECONDS);
}
return Service.START_STICKY;
}
public void setNotification() {
PendingIntent contentIntent;
contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Main_Activity.class), 0);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setColor(this.getResources().getColor(R.color.action_bar_color))
.setContentTitle("MainActivity")
.setOngoing(true)
.setAutoCancel(false)
.setContentText("MyApp");
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Notification notification = mBuilder.build();
startForeground(NOTIFICATION_ID, notification); //NOTIFICATION_ID is a random integer value which has to be unique in an app
}
}
private class mainTask implements Runnable {
public void run() {
// 1 Second Timer
}
}
有用的链接:
Run a service in the background forever..? Android
How to run background service after every 5 sec not working in android 5.1?
How to run a method every X seconds
关于android - 手机进入空闲状态时后台服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563311/