How to make service run even in sleep mode?

前端 未结 1 1581
一个人的身影
一个人的身影 2021-01-12 22:56

I have service that is implementing location listener. Now my question is how to make sure that my service will capture location even in sleep mode. I have read about alar

1条回答
  •  抹茶落季
    2021-01-12 23:20

    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.

    0 讨论(0)
提交回复
热议问题