开发者

android long running service without notification

I see this example with programs like Advance Task killer, Watch Dog, eBay, battery widgets, ect. There is a background service running that monitors device activity, a broadcastreceiver, but there is an option to disable the notification icon displayed. Currently my application works flawlessly by calling:

Contex开发者_运维知识库t context = getApplicationContext();
Intent intent = new Intent(context, SomeBackGroundService.class);
context.startService(intent) 

and then in my service I am calling:

startForeground(NOTIFICATION_ID, notification);

Now how is it that these other applications can have a long running broadcastreceiver running without a notification icon? What do I need to do in order to disable/set ect as to hide the icon and add this feature to my application?

Thanks in advance


I'm not expert on this, but I disagree with the accepted answer.

Your startForeground is key to ensuring that your service continues running.

Without that, it might keep running, but it has a much lower priority so it is much more likely to be killed by the system.


Your service is entirely independent of whether or not a notification exists for it. If you removed the line, startForeground, the service would continue to run. The only time a service stops is if you call context.stopService() or stopSelf(). Throw some logs into your service, and you'll see that it continues to run.

Override the onStartCommand to determine behavior of your service after garbage collection:

 @Override
 public int onStartCommand(Intent intent, int flags, int startId() {
      super.onStartCommand(intent, flags, startId);
      doWork();
      return START_STICKY;
 }

START_STICKY recreates your service after garbage collection. START_REDELIVER_INTENT will recreate your service after garbage collection using the original intent, use this only if you need extra intent data.


Create a notification that contains an icon made with a png and is only 1 pixel in height and width and make that pixel transparent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜