Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

java - How it is possible Service run indefinitely and also allow binding in android?

I want a service which can run in the background until I stop, even if the component that started it is destroyed and also allows binding to the activities. How it is possible ?

As per android bound services document - there are three ways of creating bound service

  1. Extending Binder class.
  2. Using Messenger.
  3. Using AIDL.

I have created a bound service using messenger (2nd method). Activity is bind to service in its onStart() method and unbind in its onStop() method. Two way messaging (between activity and service) works properly. But problem is that when activity unbinds service, service is destroyed. But I want a service which can run indefinitely.

It is possible as android Services Dev Guide - "Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start it and onBind() to allow binding."

I also implement onStartCommand() method in service and return START_STICKY, but it is never called. Looking at the lifecycle callbacks of bounded service in dev guide, there is no onStartCommand() callback method. Then how it is possible to run service until we stop and also allow binding?

I am using eclipse platform in fedora 15 OS.

Any Help.....

question from:https://stackoverflow.com/questions/7292533/how-it-is-possible-service-run-indefinitely-and-also-allow-binding-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to start it with startService() somewhere. This will prevent it from being stopped automatically when there are no more bindings.

From the Service documentation, emphasis mine:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag.

As others have pointed out, it could still be killed by Android if resources are needed. You can "prioritize" your Service and make it less likely to be killed if you make it a foreground service.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...