So there were some ways for a service not to be killed when device goes in sleep mode.
I started my service as a foreground service attached with the notification. I don't say that its the better approach for a long term service. But of-course this solution is open for more optimization. This solution doesn't get the service go in pause state while in sleep mode.
Following is the whole service code:
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
}
}
Helpful Links:
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?