1

i have created an application which will start a service to check a particular remote file for update..

the service part is done but now the user needs to manually start up the service

is there a way which i can make the service start up automatically once the application is not in view (either the user clicks the home button/clicks back or open another application)

++++++++++ANSWER++++++++++

anyway figured out how to do it already

    @Override
protected void onPause() 
{
    startService(new Intent(this, fileService.class));
    super.onPause();
}

@Override
protected void onResume() 
{
    stopService(new Intent(this, fileService.class));
    super.onResume();
}

i used this to start the service when the application is paused and stop when its resume

ben
  • 393
  • 2
  • 5
  • 14
  • why not just start it when the activity is started? – Dan D. Mar 05 '11 at 09:28
  • @Dan D my services will stop when the activity start.. so as not to interrupt the user and it is only required to start after the user closes the application. cheers :) – ben Mar 05 '11 at 10:05

2 Answers2

3

You can not do this on Application level, but on Activities level. Activities have a lifecycle, where they get notified when their status changes.

You need to implement onPause() or onStop() in your Activity.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • erm how do i go about it? mind sharing or pointing me to some good references? – ben Mar 05 '11 at 09:41
  • You already have an Activity, right? Just override methods onPause() and onStop(). Read this to understand when this methods get called: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle – Peter Knego Mar 05 '11 at 09:51
  • understand what you are talking about already but how do i override the methods? my classes extends Activity – ben Mar 05 '11 at 09:54
  • The overriding method has the same name, number and type of parameters, and return type as the method it overrides. http://download.oracle.com/javase/tutorial/java/IandI/override.html – Peter Knego Mar 05 '11 at 10:52
  • Eclipse helps you with this: http://www.java-tips.org/other-api-tips/eclipse/how-to-override-a-method-from-a-base-class-using-ec.html – Peter Knego Mar 05 '11 at 10:53
  • Note: `onCreate()` method in your activity is an example of an overridden method. It overrides the default implementation in Activity. – Peter Knego Mar 05 '11 at 10:54
1

I thought the answer should be clear and simple for futere needings.

@Override
protected void onPause() {
  startService(new Intent(this, YourService.class));
  super.onPause();
}

@Override
protected void onResume() {
  stopService(new Intent(this, YourService.class));
  super.onResume();
}
Metin Ilhan
  • 231
  • 7
  • 16