我有一个粘性的后台服务,必须一直运行。基本上它跟踪时间,它是一个自定义时钟计时器。但是一旦设备进入空闲状态(当电话屏幕关闭时),定时器(后台服务)也会暂停。
即使屏幕关闭,我该怎么做才能让它始终保持运行?
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;
}
}
答案 0 :(得分:6)
因此,当设备进入睡眠模式时,有一些方法可以使服务不被杀死。 我开始将我的服务作为附加通知的前台服务。我并不是说这是长期服务的更好方法。但当然这个解决方案可以进行更多优化。在睡眠模式下,此解决方案不会使服务进入暂停状态。
以下是整个服务代码:
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
答案 1 :(得分:0)
如果您希望将服务作为永无止境的服务,请在onStartCommand
中使用此代码@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Put code here
return START_REDELIVER_INTENT;
}
您也可以使用START_STICKY。