When to use the serviceService typeOpen serviceRunning in the backgroundService communicationAdditional ResourcesWhen to use the service:
@, any user-interface-independent operation that can be moved to a background thread, and then controlled by a service to control the thread.
Service Type:
@, first is the one, performs work for the application independent of the user ' s input.
such as: Background execution of the music player.
@, the other type of Service was one that's directly triggered by a action from the user.
For example: Photo-sharing app for photos upload service. The system terminates the service automatically after completion.
@, service life cycle:
1, for the service, will always be executed two callback methods: OnCreate and OnDestroy.
2. Complete most of the initialization work in OnCreate and do most of the cleanup work in OnDestroy.
3, since the Oncreate,ondestroy are executed in the main thread, this should move the long-running operation to the background thread.
Open service:
@, Context.startservice:
1. If you need to provide external calls, you need to configure Intent-filter.
2, call Context.startservice will trigger Onstartcommand, the system according to the return value of Onstartcommand determines whether the service is shut down after the restart.
3, Start_sticky: System for some reasons, such as insufficient memory, shut down the service, if the service Onstartcommand return Start_sticky, the system will restart the service, but the parameters intent passed in is null. In this case, you may need to save the data in OnDestroy. (music player)
4, Start_not_sticky: The service will not be restarted after the system is shut down. (Upload service)
5, Start_redeliver_intent: similar to Start_sticky, but the parameter INTENT incoming is the initial INTENT.
6. The results can be broadcastreceiver to the activity.
7. This method needs to stop the service by calling Service.stopself () or Context.stopservice ().
8, example, demo service.stopself ()
Public classMymusicplayerextendsServiceImplementsmediaplayer.oncompletionlistener{ Public Static FinalString action_add_to_queue = "Com.example.lsp.myactivity.ADD_TO_QUEUE"; PrivateConcurrentlinkedqueue<uri>Mtrackqueue; PrivateMediaPlayer Mmediaplayer; Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Super. OnCreate (); Mtrackqueue=NewConcurrentlinkedqueue<uri>(); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {String Action=intent.getaction (); if(Action_add_to_queue.equals (ACTION)) {Uri Trackuri=Intent.getdata (); Addtracktoqueue (Trackuri); } returnStart_not_sticky; } @Override Public voidOnDestroy () {Super. OnDestroy (); if(Mmediaplayer! =NULL) {mmediaplayer.release (); Mmediaplayer=NULL; } } /*** ADD track to end of queue if already palying, * otherwise create a new MediaPlayer and start playing. */ Private synchronized voidaddtracktoqueue (Uri trackuri) {if(Mmediaplayer = =NULL){ Try{Mmediaplayer= Mediaplayer.create ( This, Trackuri); Mmediaplayer.setoncompletionlistener ( This); Mmediaplayer.prepare (); Mmediaplayer.start (); }Catch(IOException e) {stopself (); } }Else{mtrackqueue.offer (Trackuri); } } //Track completed, start playing next or stop service ...@Override Public voidOncompletion (MediaPlayer MP) {Mmediaplayer.reset (); Uri Nexttrackuri=Mtrackqueue.poll (); if(Nexttrackuri! =NULL){ Try{Mmediaplayer.setdatasource ( This, Nexttrackuri); Mmediaplayer.prepare (); Mmediaplayer.start (); }Catch(IOException e) {stopself (); } }Else{stopself (); } }}
Mymusicplayer.java
@, Context.bindservice:
1. This method is used for the same in-app component that owns the service object and then accesses the service method directly through the service object. This method is called local binder.
2. If the service is called across applications, Aidl is required.
3. Any service that is not part of the current foreground running application may be terminated by the system (for free RAM). To call the Service.startforeground () method, you want the service to run after the user exits the app.
4. When the last client disconnects (Context.unbindservice ()), the service will stop automatically unless you call Service.startforeground () after disconnecting the latter client to maintain service Alive This is why it is so important to call Service.stopforeground () correctly.
Running in the background:
@, Intentservice:
1, intentservice through the handler way to achieve the background run.
2, the custom service inherits Intentservice, implements the Onhandleintent method: According to the intent Action (Intent.getaction ()), realizes the multi-action switch.
3, multiple calls, the processing of the queue, that is, onhandleintent processing only one intent at a time.
4. Example:
Public classMyintentserviceextendsIntentservice {Private Static FinalString NAME = Myintentservice.class. Getsimplename (); Public Static FinalString Action_upload_photo = "Com.example.lsp.myactivity.UPLOAD_PHOTO"; Public Static FinalString Extra_photo = "Bitmapphoto"; Public Static FinalString action_send_massage = "Com.example.lsp.myactivity.SEND_MESSAGE"; Public Static FinalString extra_message = "MessageText"; Public Static FinalString extra_recipient = "Messagerecipient"; PublicMyintentservice () {Super(NAME); //we don ' t want intents redelivered in case We ' re shut down unexpectedlySetintentredelivery (false); } /*** This methos are executed on their own thread, one intent at a time ...*/@Overrideprotected voidonhandleintent (Intent Intent) {String action=intent.getaction (); if(Action_send_massage.equals (ACTION)) {String MessageText=Intent.getstringextra (extra_message); String messagerecipient=Intent.getstringextra (extra_recipient); SendMessage (Messagerecipient, MessageText); }Else if(Action_upload_photo.equals (ACTION)) {Bitmap PHOTO=Intent.getparcelableextra (Extra_photo); Uploadphoto (photo); } } Private voidsendMessage (String messagerecipient, String messagetext) {//TODO make network call ...//TODO Send A broadcast that operation is completed } Private voidUploadphoto (Bitmap photo) {//TODO make network call ...//TODO Send A broadcast that operation is completed//Sendbroadcast (New Intent (broadcast_upload_completed)); }}
Myintentservice.java
@, Executorservice:
1. Implement parallel execution of operation.
2, the custom service class, inherits the Services class.
3. Add the Executorservice object as a member variable.
4, in the custom service class to create a private class, and implement the Runnable interface, the class to complete the specific functions of the operation.
5. Perform the operation through the Executorserive Execute method in the Onstartcommand () method.
6. Example:
Public classMediatranscoderextendsService {Private Static Final intnotification_id = 1001; Public Static FinalString Action_transcode_media = "Com.example.lsp.myactivity.TRANSCODE_MEDIA"; Public Static FinalString Extra_output_type = "OutputType"; PrivateExecutorservice Mexecutorservice; Private intMrunningjobs = 0; Private FinalObject MLock =NewObject (); Private BooleanMisforeground =false; Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Super. OnCreate (); Mexecutorservice=Executors.newcachedthreadpool (); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {String Action=intent.getaction (); if(Action_transcode_media.equals (ACTION)) {String OutputType=Intent.getstringextra (Extra_output_type); //Start New job and increase the running job counter synchronized(mLock) {transcoderunnable transcoderunnable=Newtranscoderunnable (Intent.getdata (), outputtype); Mexecutorservice.execute (transcoderunnable); Mrunningjobs++; Startforegroundifneeded (); } } returnStart_not_sticky; } @Override Public voidOnDestroy () {Super. OnDestroy (); Mexecutorservice.shutdownnow (); synchronized(mLock) {mrunningjobs= 0; Stopforegroundifalldone (); } } Public voidstartforegroundifneeded () {if(!misforeground) {Notification Notification=Buildnotificatin (); Startforeground (notification_id, NOTIFICATION); Misforeground=true; } } PrivateNotification Buildnotificatin () {Notification Notification=NULL; //TODO Build the notification here returnnotification; } Private voidStopforegroundifalldone () {if(Mrunningjobs = = 0 &&misforeground) {Stopforeground (true); Misforeground=false; } } Private classTranscoderunnableImplementsrunnable{PrivateUri Mindata; PrivateString Moutputtype; Privatetranscoderunnable (Uri inData, String outputtype) {mindata=InData; Moutputtype=OutputType; } @Override Public voidrun () {//TODO Perform transcoding here ...//Decrease counter when we ' re done. synchronized(mLock) {mrunningjobs--; Stopforegroundifalldone (); } } }}
Mediatranscoder.java
Service communication:
@, how to use Broadcastreceiver
@, on the basis of Bindservice () mode, add callback interface to implement communication
1. Example:
Mylocalservice.java
Myactivity.java
Additional Resources:
Google ' s changes to the Service API at
Http://android-developers.blogspot.se/2010/02/service-api-changes-starting-with.html
Dianne Hackborn at
Http://android-developers.blogspot.se/2010/04/multitaskingandroid-way.html
Android programming:pushing The Limits--Chapter 6:services and Background Tasks