도래울

Android Service Lifecycle 본문

개발/Android

Android Service Lifecycle

도래울 2016. 2. 5. 13:06

Service Lifecycle


Next, we want to override some of the main lifecycle methods:

 

  1. onCreate() Called when the service is created first time.
  2. onStartCommand() Called when the service is started.
  3. onDestroy() Called when the service is terminated.

To do that, you can use Eclipse tool Source→Override/Implement Methods and select those three methods.

At this point, in spirit of producing a minimally working app at each stage of learning, we’ll write just a little code that logs a note in each of the overridden methods. So the shell of our service looks like this:

 

package com.marakana.yamba3;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class UpdaterService1 extends Service {
  static final String TAG = "UpdaterService"; // 

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

  @Override
  public void onCreate() { // 
    super.onCreate();
    Log.d(TAG, "onCreated");
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) { // 
    super.onStartCommand(intent, flags, startId);
    Log.d(TAG, "onStarted");
    return START_STICKY;
  }

  @Override
  public void onDestroy() { // 
    super.onDestroy();
    Log.d(TAG, "onDestroyed");
  }
}


As in all major classes, I like to add the TAG constant because I use Log.d() quite a bit.

onBind() is used in bound services to return the actual implementation of something called a Binder. Since we are not using a bound service, we can just return null here.

onCreate() is called when the service is initially created. It is not called for subsequent startService() calls, so it is a good place to do work that needs to be done only once during the life of a service.

onStartCommand() is called each time service receives a startService() intent to get started. A service that is already stated could get multiple requests to start again, and each will cause onStartCommand() to execute.

onDestroy() is called just before the service is destroyed by stopService() request. This is a good place to clean up things that might have been initialized in onCreate().

Update the Manifest File

Now that we have the shell of our service, we have to define it in the manifest file just like any other main building block, otherwise we won’t be able to call our service. Simply open AndroidManifest.xml, click on the right-most tab to see the raw XML code, and add the following within the <application> element:

...
  <application android:icon="@drawable/icon" android:label="@string/app_name">
     ...
     <service android:name=".UpdaterService" /> <!--  -->
     ...
  </application>
...

 

UpdaterService definition.

Services are equal to activities as Android building blocks, so they appear at the same level in the manifest file.


Comments