Destroying a service as soon as the app is killed - android

I need to create a service that will run as much as app will be running. I know that the most straightforward solution would be to bind service in my Application class but this class does not have onDestroy onStop or onPause methods so unbinding is not possible... sadly... Other approach is to bind service to my base activity (and other activities will extend that activity) and for example onResume bind and onStop unbind service. But then service will be always recreated... And that is not I want. Is it possible to have continuously running service and destroy it as soon as application closed? Here's the second approach (this code is in my base activity)
protected void onResume() {
super.onResume();
if (service == null && !isBound) {
bindService(new Intent(this, NetworkListenerService.class), mServiceConnection, BIND_AUTO_CREATE);
}
}
#Override
protected void onPause() {
super.onPause();
if (isBound) {
unbindService(mServiceConnection);
isBound = false;
}
}

Set the below attribute in your service tag in the manifest file,
<service android:name="service" android:stopWithTask="true"/>
adding this will call the ondestroy() of the service when the task is removed.

Related

android: how to receive broadcast from service when the app is inactive

When my service is running and I can see my app on the screen, everything works fine. My service sends broadcast messages and I can see them in my "MainActivity". But as soon as I push the home button and my app is no longer in the foreground, it stops. The service is still running but the broadcasts don't arrive at my "dead" or "pausing" app. This is my code:
Main Activity:
onCreate:
Intent intent = new Intent(getApplicationContext(), MainGate_Service.class);
startService(intent);
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}
#Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
}
private BroadcastReceiver ServiceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("ServiceMessage");
if(message != null) {
if(alarmActive && message.equals("ring"))
new soundPlayer().execute();
}
setNoti(message);
}
}
Service:
#Override
protected void onHandleIntent(Intent intent) {
ring = rcv_ring();
Intent ServiceIntent = new Intent("MainGate_ring");
ServiceIntent.putExtra("ServiceMessage", ring);
LocalBroadcastManager.getInstance(this).sendBroadcast(ServiceIntent);
}
whenever you press home button onStop gets call and there you are unregister receiver so there is not broadcast receiver who can receive broadcast.
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
Remove above line from onStop() or unregister it whenever your service stop.
onStop#LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
literally unregister receiver. So there is no receiver to receive broadcasted message from service.
The problem is here
#Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
}
Activity.onStart() :
Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().
Activity.onStop()
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
So as soon as you leave your activity onStop() is called and you unregister your receiver.
Don't put your unregister code in onDestroy() either, because it may or may not be called and the Activity might be killed without calling it.
As suggested by #Naveen Dissanayake you might want to reconsider your logic.
You register your BroadcastReceiver inside activity, so, it will depend on Activity's lifecycle. When you press back button, activity goes into 'stopped' state - methods onPause and onStop is called. Android can also destroy this activity in it is low on resources.
Service, on the other hand, i smeant to be running inndefinetely, even when ui is not ready. If you wanat to receive notifications from Activity, there is two
possible solutions:
- Create, store and manage BroadcastReceiver in Application instance - Application class is still running until your app is destroyed. It seems like you want to play sound when service notify you about some action.
Register BroadcastReceiver in onCreate and unregister in onDestroy in notifications.
- Another solution - use another Service if you want to trigger some action or IntentService, reacting to that broadcast.
I woud consider solution - create some ResponseService, start it along with your MainGate_Service (from Application) and stop it from application too. In that Service register BroadcastReceiver or, add IntentFilter into manifest if you want it to start even when app is not running. In your Activity, bind to that service. Serive will know if some UI is attached (if Activity is bound), and, if it is, will notify activity. If it don't - will do some other things (perhaps, show notification)
If you want to receive Broadcast even if your Activity is in
Background then,
Register in onCreate(...)
#Override
protected void onCreate(Bundle sis) {
super.onCreate(sis);
setContentView(...);
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}
Unregister in onDestroy()
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}

onUnbind not being called when binding the activity to a running service

I have this activity that starts and binds to a service:
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(context, SoundService.class);
context.startService(intent);
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
and I unbind by:
#Override
protected void onStop() {
context.unbindService(serviceConnection);
super.onStop();
}
The service keeps running even after closing the activity. Look at this scenario:
Activity starts the service and binds to it
Activity gets killed, the service keeps running, onUnbind() is called
Activity starts again, and binds to the running service
Activity gets killed, onUnbind() is not called :(
Why is the onUnbind() not being called?
return true from onUnbind, next time if you call bindService again not only onRebind will be called but also when the last clients unbinds also onUnbind will be called by the system
How did you start the service ? Please paste that code.
Service will only be stopped after you called unbindService() IF there are no other clients connected to this service AND the service was started with bind call with AUTO_CREATE. If the service was started with startService() then the service will not be stopped until the service calls stopSelf() or android terminates it to free memory

Communicate with foreground service android

First question here, but I've been around for a while.
What do I have:
I'm building an Android app which plays audio streams and online playlists. Everything is working fine now, but I'm having issues in communicating with my service.
The music is playing in a Service, started with startForeground, so it doesn't gets killed.
I need to communicate from my activity with the service, for getting the track name, image, and a couple of things more.
Whats my issue:
I think I need to start my service with bindService (instead of my current startService) so the activity can talk to it.
However, when I do that, my service gets killed after closing the Activity.
How can I get both? Binding and foreground service?
Thanks!
No. bindService will not start a service . It will just bind to the Service with a service connection, so that you will have the instance of the service to access/control it.
As per your requirement I hope you will have the instance of MediaPlayer in service . You can also start the service from Activity and then bind it. If the service is already running onStartCommand() will be called, and you can check if MediaPlayer instance is not null then simply return START_STICKY.
Change you Activity like this..
public class MainActivity extends ActionBarActivity {
CustomService customService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start the service, even if already running no problem.
startService(new Intent(this, CustomService.class));
// bind to the service.
bindService(new Intent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
// now you have the instance of service.
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
customService = null;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (customService != null) {
// Detach the service connection.
unbindService(mConnection);
}
}
}
I have similar application with MediaPlayer service. let me know if this approach doesn't help you.
Quoting Android documentation:
A bound service is destroyed once all clients unbind, unless the service was also started
And about the difference between started and bound just take a look to https://developer.android.com/guide/components/services.html
So, you have to create the Service using startService and then bindService, like #Libin does in his/her example. Then, the service will run until you use stopService or stopSelf or until Android decides that it needs resources and kills you.

How to unbind a Service when the Activity Stops?

I'm trying to make a music player. To do that I'm creating a service that manages a MediaPlayer object and plays the songs. But every time I reopen my music application it starts a new Service and keeps playing two songs simultaneously. How can I make my Activity bind to the already running service?
I noticed that when I don't call unbindService (...) in the OnStop() method my application runs OK. But I don't know if its right to not unbind when the activity stops.
I'm binding like that:
#Override
protected void onStart() {
super.onStart();
Intent service = new Intent(this,MyService.class);
bindService(service, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if(mBound) {
unbindService(mConnection);
mBound = false;
}
}
You need to check on onStart() that is service running or not. If service is already running, then you need to just bind it. But in your current code you creating service everytime.
You should try to use Service.START_STICKY for checking that service is already running or not. You can see :
Service
, start Sticky or start not sticky
I think it will help you to update your service class.
I could fix it add startService(...) to the OnStart( ) method. I didnt understand why this fixed, but seems that I need to do that. If anyone knows why please add. Thanks for everyone help.
this is how OnStart got:
#Override
protected void onStart() {
super.onStart();
Intent service = new Intent(this,MyService.class);
bindService(service, mConnection, Context.BIND_AUTO_CREATE);
startService(service);
}

Android bindService or/and startService

I want to create Service using bindService method.
But when I close one Activity my Service is destroyed, and I don't want that.
I try to put service in foreground using startForeground(NOTIFICATION_ID, notification); service onCreate , but service still destroy.
Now I try with call two methods for starting Service at same time :
Intent bindIntent= new Intent(this, ServiceC.class);
startService(bindIntent);
bindService(bindIntent, onService, BIND_AUTO_CREATE);
By calling these two methods Service not destroyed. My app work fine with this method.
Can someone explain to me whether this is a good way or if it is not can you please give me idea why startForeground(NOTIFICATION_ID, notification); does not work ?
What is the best way to use bindService but at the same time I don't want the service to self destroy.
I Used the same solution and it's a legitimate one. From Service ref:
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. Once
neither of these situations hold, the
service's onDestroy() method is called
and the service is effectively
terminated.
startForeground() is not working because it just tries to prevent the service from being killed by the system, but its lifecycle is another thing: if nothing is more bound to that service and it wasn't started, it just stops.
If you start service with startService() it is not destroyed. Tried starting a service, which extends IntentService and have a loop in onHandleIntent(). When loop is finished, then service destroyed and it is not related with Activity finish. User can close application, but service is not being killed.
public class MyService extends IntentService
{
private static final String serviceName = "MyService ";
public MyService () {
super(serviceName);
}
#Override
public void onDestroy()
{
Log.v(serviceName, "onDestroy");
Toast.makeText(this, serviceName+" stopped", Toast.LENGTH_LONG).show();
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent arg0) {
long endTime = System.currentTimeMillis() + 30*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
Log.v(serviceName, "Service loop");
wait(1000);
} catch (Exception e) {
}
}
}
}
}

Categories

Resources