Книга: Beginning Android

Service with Class

Service with Class

Creating a service implementation shares many characteristics with building an activity. You inherit from an Android-supplied base class, override some lifecycle methods, and hook the service into the system via the manifest.

The first step in creating a service is to extend the Service class, in our case with our own WeatherPlusService subclass.

Just as activities have onCreate(), onResume(), onPause() and kin, Service implementations can override three different lifecycle methods:

1. onCreate(), which, as with activities, is called when the service process is created

2. onStart(), which is called when a service is manually started by some other process, versus being implicitly started as the result of an IPC request (discussed more in Chapter 31)

3. onDestroy(), which is called as the service is being shut down.

Common startup and shutdown logic should go in onCreate() and onDestroy();onStart() is mostly if your service needs data passed into it from the starting process and you don’t wish to use IPC.

For example, here is the onCreate() method for WeatherPlusService:

@Override
public void onCreate() {
 super.onCreate();
 client = new DefaultHttpClient();
 format = getString(R.string.url);
 myLocationManager =
 (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 myLocationManager.requestLocationUpdates("gps", 10000,
  10000.0f, onLocationChange);
}

First, we chain upward to the superclass, so Android can do any setup work it needs to have done. Then we initialize our HttpClient and format string as we did in the Weather demo. We then get the LocationManager instance for our application and request to get updates as our location changes, via the gps LocationProvider, which will be discussed in Chapter 33.

The onDestroy() method is much simpler:

@Override
public void onDestroy() {
 super.onDestroy();
 myLocationManager.removeUpdates(onLocationChange);
}

Here, we just shut down the location-monitoring logic, in addition to chaining upward to the superclass for any Android internal bookkeeping that might be needed.

In addition to those lifecycle methods, though, your service also needs to implement onBind(). This method returns an IBinder, which is the linchpin behind the IPC mechanism. If you’re creating a service class while reading this chapter, just have this method return null for now, and we’ll fill in the full implementation in the next section.

Оглавление книги


Генерация: 0.917. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз