FileDocCategorySizeDatePackage
ServiceStartArguments.javaAPI DocGoogle Android v1.5 Example5461Sun Nov 11 13:01:04 GMT 2007com.google.android.samples.app

ServiceStartArguments

public class ServiceStartArguments extends android.app.Service implements Runnable
This is an example of implementing an application service that runs locally in the same process as the application. The {@link ServiceStartArgumentsController} class shows 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 android.content.Intent
mInvokeIntent
private volatile android.os.Looper
mServiceLooper
private volatile ServiceHandler
mServiceHandler
Constructors Summary
Methods Summary
public android.os.IBindergetBinder()

        return null;
    
protected voidonCreate()

        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // This is who should be launched if the user selects our persistent
        // notification.
        mInvokeIntent = new Intent(this, ServiceStartArgumentsController.class);

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread thr = new Thread(null, this, "ServiceStartArguments");
        thr.start();
    
protected voidonDestroy()

        while (mServiceLooper == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }
        mServiceLooper.quit();

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

        // Tell the user we stopped.
        mNM.notifyWithText(R.string.service_arguments_stopped,
                   getText(R.string.service_arguments_stopped),
                   NotificationManager.LENGTH_SHORT,
                   null);
    
protected voidonStart(int startId, android.os.Bundle arguments)

        System.out.println("Starting #" + startId + ": " + arguments);
        while (mServiceHandler == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }

        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = arguments;
        mServiceHandler.sendMessage(msg);
        Log.i("ServiceStartArguments", "Sending: " + msg);
    
public voidrun()

        Looper.prepare();

        mServiceLooper = Looper.myLooper();
        mServiceHandler = new ServiceHandler();

        Looper.loop();