FileDocCategorySizeDatePackage
LocalService.javaAPI DocAndroid 1.5 API3875Wed May 06 22:41:08 BST 2009com.example.android.apis.app

LocalService

public class LocalService extends android.app.Service
This is an example of implementing an application service that runs locally in the same process as the application. The {@link LocalServiceController} and {@link LocalServiceBinding} classes show how to interact with the service.

Notice the use of the {@link NotificationManager} when interesting things happen in the service. This is generally how background services should interact with the user, rather than doing something more disruptive such as calling startActivity().

Fields Summary
private android.app.NotificationManager
mNM
private final android.os.IBinder
mBinder
Constructors Summary
Methods Summary
public android.os.IBinderonBind(android.content.Intent intent)

        return mBinder;
    
public voidonCreate()

        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
    
public voidonDestroy()

        // Cancel the persistent notification.
        mNM.cancel(R.string.local_service_started);

        // Tell the user we stopped.
        Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    
private voidshowNotification()
Show a notification while this service is running.


                 
       
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.local_service_started);

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.local_service_started, notification);