<manifest...> ... <application> <service android:name=".ExampleService" /> ... </application> </manifest>
publicclassHelloIntentServiceextendsIntentService{ /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ publicHelloIntentService(){ super("HelloIntentService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protectedvoid onHandleIntent(Intent intent){ // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime =System.currentTimeMillis()+5*1000; while(System.currentTimeMillis()< endTime){ synchronized(this){ try{ wait(endTime -System.currentTimeMillis()); }catch(Exception e){ } } } } }
@Override publicint onStartCommand(Intent intent,int flags,int startId){ Toast.makeText(this,"service starting",Toast.LENGTH_SHORT).show(); returnsuper.onStartCommand(intent,flags,startId); }
publicclassHelloServiceextendsService{ privateLooper mServiceLooper; privateServiceHandler mServiceHandler; // Handler that receives messages from the thread privatefinalclassServiceHandlerextendsHandler{ publicServiceHandler(Looper looper){ super(looper); } @Override publicvoid handleMessage(Message msg){ // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. long endTime =System.currentTimeMillis()+5*1000; while(System.currentTimeMillis()< endTime){ synchronized(this){ try{ wait(endTime -System.currentTimeMillis()); }catch(Exception e){ } } } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); } } @Override publicvoid onCreate(){ // 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. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread thread =newHandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler =newServiceHandler(mServiceLooper); } @Override publicint onStartCommand(Intent intent,int flags,int startId){ Toast.makeText(this,"service starting",Toast.LENGTH_SHORT).show(); // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); // If we get killed, after returning from here, restart return START_STICKY; } @Override publicIBinder onBind(Intent intent){ // We don't provide binding, so return null return null; } @Override publicvoid onDestroy(){ Toast.makeText(this,"service done",Toast.LENGTH_SHORT).show(); } }
Intent intent =newIntent(this,HelloService.class); startService(intent);如果该Intent还未运行,那么系统会先调用onCreate(),然后调用onStartCommand()。
publicclassLocalServiceextendsService{ // Binder given to clients privatefinalIBinder mBinder =newLocalBinder(); // Random number generator privatefinalRandom mGenerator =newRandom(); /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ publicclassLocalBinderextendsBinder{ LocalService getService(){ // Return this instance of LocalService so clients can call public methods returnLocalService.this; } } @Override publicIBinder onBind(Intent intent){ return mBinder; } /** method for clients */ publicint getRandomNumber(){ return mGenerator.nextInt(100); } } publicclassBindingActivityextendsActivity{ LocalService mService; boolean mBound =false; @Override protectedvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protectedvoid onStart(){ super.onStart(); // Bind to LocalService Intent intent =newIntent(this,LocalService.class); bindService(intent, mConnection,Context.BIND_AUTO_CREATE); } @Override protectedvoid onStop(){ super.onStop(); // Unbind from the service if(mBound){ unbindService(mConnection); mBound =false; } } /** Called when a button is clicked (the button in the layout file attaches to * this method with the android:onClick attribute) */ publicvoid onButtonClick(View v){ if(mBound){ // Call a method from the LocalService. // However, if this call were something that might hang, then this request should // occur in a separate thread to avoid slowing down the activity performance. int num = mService.getRandomNumber(); Toast.makeText(this,"number: "+ num,Toast.LENGTH_SHORT).show(); } } /** Defines callbacks for service binding, passed to bindService() */ privateServiceConnection mConnection =newServiceConnection(){ @Override publicvoid onServiceConnected(ComponentName className, IBinder service){ // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder =(LocalBinder) service; mService = binder.getService(); mBound =true; } @Override publicvoid onServiceDisconnected(ComponentName arg0){ mBound =false; } }; }
publicclassMessengerServiceextendsService{ /** Command to the service to display a message */ staticfinalint MSG_SAY_HELLO =1; /** * Handler of incoming messages from clients. */ classIncomingHandlerextendsHandler{ @Override publicvoid handleMessage(Message msg){ switch(msg.what){ case MSG_SAY_HELLO: Toast.makeText(getApplicationContext(),"hello!",Toast.LENGTH_SHORT).show(); break; default: super.handleMessage(msg); } } } /** * Target we publish for clients to send messages to IncomingHandler. */ finalMessenger mMessenger =newMessenger(newIncomingHandler()); /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ @Override publicIBinder onBind(Intent intent){ Toast.makeText(getApplicationContext(),"binding",Toast.LENGTH_SHORT).show(); return mMessenger.getBinder(); } } publicclassActivityMessengerextendsActivity{ /** Messenger for communicating with the service. */ Messenger mService =null; /** Flag indicating whether we have called bind on the service. */ boolean mBound; /** * Class for interacting with the main interface of the service. */ privateServiceConnection mConnection =newServiceConnection(){ publicvoid onServiceConnected(ComponentName className,IBinder service){ // This is called when the connection with the service has been // established, giving us the object we can use to // interact with the service. We are communicating with the // service using a Messenger, so here we get a client-side // representation of that from the raw IBinder object. mService =newMessenger(service); mBound =true; } publicvoid onServiceDisconnected(ComponentName className){ // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. mService =null; mBound =false; } }; publicvoid sayHello(View v){ if(!mBound)return; // Create and send a message to the service, using a supported 'what' value Message msg =Message.obtain(null,MessengerService.MSG_SAY_HELLO,0,0); try{ mService.send(msg); }catch(RemoteException e){ e.printStackTrace(); } } @Override protectedvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protectedvoid onStart(){ super.onStart(); // Bind to the service bindService(newIntent(this,MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); } @Override protectedvoid onStop(){ super.onStop(); // Unbind from the service if(mBound){ unbindService(mConnection); mBound =false; } } }
LocalService mService; privateServiceConnection mConnection =newServiceConnection(){ // Called when the connection with the service is established publicvoid onServiceConnected(ComponentName className,IBinder service){ // Because we have bound to an explicit // service that is running in our own process, we can // cast its IBinder to a concrete class and directly access it. LocalBinder binder =(LocalBinder) service; mService = binder.getService(); mBound =true; } // Called when the connection with the service disconnects unexpectedly publicvoid onServiceDisconnected(ComponentName className){ Log.e(TAG,"onServiceDisconnected"); mBound =false; } }; Intent intent =newIntent(this,LocalService.class); bindService(intent, mConnection,Context.BIND_AUTO_CREATE);
Notification notification =newNotification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); Intent notificationIntent =newIntent(this,ExampleActivity.class); PendingIntent pendingIntent =PendingIntent.getActivity(this,0, notificationIntent,0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION, notification);
publicclassExampleServiceextendsService{ int mStartMode; // indicates how to behave if the service is killed IBinder mBinder; // interface for clients that bind boolean mAllowRebind;// indicates whether onRebind should be used @Override publicvoidonCreate(){ // The service is being created } @Override publicintonStartCommand(Intent intent,int flags,int startId){ // The service is starting, due to a call to startService() returnmStartMode; } @Override publicIBinderonBind(Intent intent){ // A client is binding to the service with bindService() returnmBinder; } @Override publicbooleanonUnbind(Intent intent){ // All clients have unbound with unbindService() returnmAllowRebind; } @Override publicvoidonRebind(Intent intent){ // A client is binding to the service with bindService(), // after onUnbind() has already been called } @Override publicvoidonDestroy(){ // The service is no longer used and is being destroyed } }