Android Service: Should It Be Declared As A Process Or Not?
Solution 1:
Create a base Activity
and call bindService
in onStart
, unbindService
in onStop
.
publicclassBaseActivityextendsActivity {
@OverridepublicvoidonStart() {
// ...bindService(intent, serviceConnection, flags);
}
@OverridepublicvoidonStop() {
// ....unbindService(serviceConnection);
}
}
This will make sure every activity that extends base is bound to the service.
When last activity is unbound from the service, it will be stopped. If you want to avoid that, call startService
first, and then bind to it. This will prevent service from stopping even if you don't have running activities.
Should the Service in this case be declared as a stand-alone process?
In your case, you don't need a separate process for your service.
Also, my Service starts a separate thread, but never stops it. Should my code stop the thread?
If you want to stop your service, you should stop your thread because thread is a GC root, and all objects accessible from it will remain in memory. So, infinite thread that is not used is a memory leak.
You can implement threading different ways depending on your requirements. You can either implement a regular thread in your Service
, or a ThreadPoolExecutor
or a Handler
. Pick a solution that fits to your needs.
Solution 2:
You can start your Service in your custom Application class. This way the service will be started only when your application is started.
For example:
publicclassMainApplicationextendsApplication {
@OverridepublicvoidonCreate() {
super.onCreate();
starService();
}
publicvoidstarService() {
Intenti=newIntent(this, YourService.class);
this.startService(i);
}
}
Solution 3:
While the other answers ere good, you might want to ask this: "Does this service needs to keep on running while the application is not, and will not run?"
- If so: create as an independant service
- If not: extend a helper class that implements the bind/unbind and have Activities extend that.
Post a Comment for "Android Service: Should It Be Declared As A Process Or Not?"