Dhana
Dhana

Reputation: 554

How to stop the Service when come back from Activity in android?

I have created the Service in android and it has running when go to the MapActivity, if i come back from MapActivity using back button, i want to stop the service. how to do that?

Upvotes: 1

Views: 143

Answers (5)

NickT
NickT

Reputation: 23873

I use a Bound Service which I bind to in activitys' onStart() and unbind from in onStop(). I bind using Context.BIND_AUTO_CREATE, so that the service stops automatically when no activity is bound to it. It is a convenient way of letting more than one activity use the service and of passing data from activity to the service through an IBinder interface

Upvotes: 0

varun257
varun257

Reputation: 296

@Override

void onDestroy
{
unbindService(ServiceConnection c);
}

Upvotes: 0

user1357696
user1357696

Reputation:

When you using the device backbutton for navigate to previous class , then use write:

@Override
public void onBackPressed(){
 //stop your Service here
}

If you used custom back button for navigate to previous class, then maintain static boolean variable in second class.

Second class: static boolean navigate = false;
when you click the custom back button in second class, then  make boolean as true;

now, in first class check the value for true: 
if it is ture , then stop the service by using Context.stopService(serviceObject);

Upvotes: 0

Lucifer
Lucifer

Reputation: 29632

You can use Context.stopService(serviceObject); to stop service from an Activity.

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93842

@Override
public void onBackPressed(){
 //stop your Service here
}

Upvotes: 1

Related Questions