Sanjeev
Sanjeev

Reputation: 292

How to stop service the service when android app has been closed

I am developing a app where I need to updated my values every 15 min. For that i am using services.I came across different types of services. Like for long running services we use simple service and, for interacting for other components we use bind service, foreground service. etc....

My situation is like i need to run the service for every 15 min when my app is open and stop the service when my app is closed

I have tried with bind service using http://www.truiton.com/2014/11/bound-service-example-android/ but i am unable to do that,I am unable to run the service every 15 min can any one help me. Thanks in advance.

Upvotes: 1

Views: 3241

Answers (2)

Varun Kumar
Varun Kumar

Reputation: 1261

To start the service when your app starts, start it in onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);

}

To stop the service, you can implement the code in 3 different methods namely, onPause(), onStop() and onDestroy().

Calling stopService() in onPause() will stop the service as soon as some other event happens on your device like a phone call, which is not best way to stop since the user will return back to the Activity immediately as soon as the call finishes.

Calling stopService() in onDestroy() is also not the best solution because onDestroy is not called in all the ways a user can close an Android app.

Therefore, the best way to stop the service is by calling stopService() in the onStop() method as shown below.

@Override
protected void onStop() {
    super.onStop();
    Intent intent = new Intent(MainActivity.this, MyService.class);
    stopService(intent);
}

Upvotes: 1

Sagar Nayak
Sagar Nayak

Reputation: 2218

If you want to stop service when your activity is closing then you have to implement the code inside onDestroy().

Below is an example-

@Override
protected void onDestroy() {
    super.onDestroy();

    Intent intent = new Intent(MainActivity.this, MyService.class);
    stopService(intent);
}

This will your stop your service.

Unless you don't call finish() in the activity or you explicitly stop the app the onDestroy() don't gets called and your service will run even your calling activity is onPause (in background).

Similarly if you want to start your service activity start you implement in onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);
}

let me know if it help your problem .

Upvotes: 0

Related Questions