所以當設備進入睡眠模式時,有一些服務不會被殺死。 我開始將我的服務作爲通知附帶的前臺服務。我不認爲它是長期服務的更好方法。但是,當然這個解決方案是爲了更多的優化而打開的。此解決方案在睡眠模式下不會使服務進入暫停狀態。
以下是整個服務代碼:
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
How to make service run even in sleep mode?
part-1 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart
part-2 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart
Android - implementing startForeground for a service?
你可以請把你的代碼.. – pkgrover
你有你的清單'wakeLock'許可? –
是的,我有。但它會耗盡電池。我正在尋找優化的解決方案。但隨時也可以分享該解決方案。由於該服務需要始終運行。 –