1

I'm aware many questions regarding how to stop a service have been asked before, but I didn't find one addressing my particular problem.

In my application I have a number of activities that communicate with one central service. For each activity I call bindService() in their onResume() methods and unbindService() in their onPause() methods. The issue I'm having with this is that each time I switch between two activities the service is destroyed and then recreated from scratch.

In order to address this I have considered calling startService() in onCreate(), to ensure the service remains active.

My question is, where should I put the stopService()-Method to ensure it is called when leaving the application? Or alternatively, is there a another way to keep the service running as I switch between two activities, without relying startService()?

summon
  • 418
  • 5
  • 11

2 Answers2

2

See android service startService() and bindService() for a comprehensive answer.

Community
  • 1
  • 1
Rajath
  • 11,787
  • 7
  • 48
  • 62
  • Thanks for your fast response. I understand that I need to call stopService() at some point. My problem is I'm not sure where to put it. I want to make sure that the service remains running until the user exits the app (i.e. all of the activities are paused or destroyed). onDestroy() doesn't seem to be the right place, as we can't rely on it being called. – summon Apr 28 '11 at 10:03
  • One way i can think of is to have a background thread in your service that checks if any bound activites are still present, and if not, call stopSelf(). – Rajath Apr 28 '11 at 10:10
  • Thank you again! Using a background thread solved my problem. – summon Apr 28 '11 at 12:17
1

this is how i stop and start the service
check this link for more details.

public void onClick(View src) {
    switch (src.getId()) {
        case R.id.buttonStart:
            Log.d(TAG, "onClick: starting srvice");
            startService(new Intent(this, MyService.class));
            break;
        case R.id.buttonStop:
            Log.d(TAG, "onClick: stopping srvice");
            stopService(new Intent(this, MyService.class));
            break;
    }
}

and in services class:

public class MyService extends Service {
    private static final String TAG = "MyService";


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");


    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");

    }
}

HAPPY CODING!

Intrications
  • 16,782
  • 9
  • 50
  • 50
dondondon
  • 881
  • 8
  • 4