Hintergrund-Dienste

Oft ist es nötig, länger andauernde Vorgänge im Hintergrund ablaufen zu lassen. Diese Vorgänge besitzen keine Benutzerschnittstelle und können mit der Klasse android.app.Service realisiert werden. In diesem Tutorial wird ein einfacher Service erstellt, welcher alle fünf Sekunden eine Nachricht ausgibt.

Als erstes wird ein neues Projekt angelegt. Anschließend wird eine Subklasse von android.app.IntentService erstellt und einige Callback-Methoden implementiert. Außerdem muss der Service in der Manifest-Datei eingetragen werden:

import android.app.IntentService;
import android.content.Intent;

public class MyService extends IntentService {

    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent arg) {
    }

}
<manifest ... >
    ...
    <application ... >
        <service android:name=".MyService" />
        ...
    </application>
</manifest>

Um den Service zu starten, wird in der Activity an der gewünschten Stelle ein Intent erstellt und die Methode startService() aufgerufen:

package de.hszg.mobileapps.services;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class ServiceTestActivity extends Activity {
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }
    
}

Nun muss natürlich noch die Methode onHandleIntent() vervollständigt werden. Der Service soll drei mal alle fünf Sekunden eine Nachricht ausgeben. Für die Ausgabe werden diesmal nicht Toast-Nachrichten sondern Statusbar-Nachrichten verwendent. Die gesamte Service-Klasse sieht nun wie folgt aus:

package de.hszg.mobileapps.services;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class MyService extends IntentService {

    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        for (int i = 0; i < 3; ++i) {
            sendNotification(i);

            synchronized (this) {
                try {
                    wait(5000);
                } catch (Exception e) {
                }
            }
        }
    }

    private void sendNotification(int i) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.ic_launcher;
        CharSequence tickerText = "Message: " + i;
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);

        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello from the service!";
        Intent notificationIntent = new Intent(this, MyService.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        mNotificationManager.notify(i, notification);
    }

}