How to make service run even in sleep mode?

喜你入骨 提交于 2019-12-01 17:49:28

If you want to ensure that your service is not killed/reclaimed by the OS you need to make it a foreground service. By default all services are background, meaning they will be killed when the OS needs resources. For details refer to this doc

Basically, you need to create a Notification for your service and indicate that it is foreground. This way the user will see a persistent notification so he knows your app is running, and the OS will not kill your service.

Here is a simple example of how to create a notification (do this in your service) and make it foreground:

Intent intent = new Intent(this, typeof(SomeActivityInYourApp));
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,   PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

builder.setSmallIcon(Resource.Drawable.my_icon);
builder.setTicker("App info string");
builder.setContentIntent(pi);
builder.setOngoing(true);
builder.setOnlyAlertOnce(true);

Notification notification = builder.build();

// optionally set a custom view

startForeground(SERVICE_NOTIFICATION_ID, notification);

Please note that the above example is rudimentary and does not contain code to cancel the notification, amongst other things. Also, when your app no longer needs the service it should call stopForeground in order to remove the notification and allow your service to be killed, not doing so is a waste of resources.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!