Android Service startup mode

Source: Internet
Author: User

1.context.startservice () mode start

Life cycle of ①context.startservice () mode:,startservice–> onCreate () –> OnStart () at startup,stopservice–> OnDestroy () If the caller exits without stopping service, the service will always run the Context.startservice () method in the background, and when the service is not created, the system calls the service's OnCreate () method first, and then calls OnStart ( Method If the StartService () method is called before the service has been created, calling the StartService () method multiple times does not cause the service to be created more than once, but results in multiple calls to the OnStart () method. Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the service ends with a call to the OnDestroy () method with code

2.context.bindservice () mode start: ①context.bindservice () mode life cycle: Binding, Bindservice-onCreate () –> onbind () caller exited, That is, the Srevice will Unbindservice–>onunbind () –> ondestory () Context.bindservice () mode to start Service method: Binding service requires three parameters: Bindservice (Intent, Conn, service.bind_auto_create); First: Intent object Second: Serviceconnection object, creating the object to implement it's onserviceconnected () and onservicedisconnected () To determine whether the connection was successful or disconnected the third: How to create a service, usually specify the binding when the automatic creation of the attached code

 Packagecom.dada.test;Importandroid.app.Activity;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportCom.dada.test.BindService.MyBinder; Public classTestactivityextendsActivity {Private BooleanFlag; Private Static FinalString TAG = "Testactivity"; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.main); Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.main); Button btnstart=(Button) Findviewbyid (R.id.btnstart); Button Btnstop=(Button) Findviewbyid (r.id.btnstop); Btnstart.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//Start Service Mode 2Bindservice ();                 }         }); Btnstop.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//Stop service Mode 2Unbindservice ();     }         }); }        //Start Service Mode 2//    Private voidBindservice () {Intent Intent=NewIntent (testactivity. This, Bindservice.class); LOG.I (TAG,"Bindservice ()");    Bindservice (Intent, Conn, context.bind_auto_create); }        Private voidUnbindservice () {log.i (TAG,"Unbindservice () Start ...."); if(Flag = =true) {log.i (TAG,"Unbindservice () flag");            Unbindservice (conn); Flag=false; }    }    PrivateServiceconnection conn =Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method StubLOG.I (TAG, "onservicedisconnected ()"); } @Override Public voidonserviceconnected (componentname name, IBinder service) {//TODO auto-generated Method StubLOG.I (TAG, "onserviceconnected ()"); Mybinder Binder=(mybinder) service; Bindservice Bindservice=Binder.getservice1 ();            Bindservice.mymethod (); Flag=true; }    };}
 Packagecom.dada.test;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportAndroid.util.Log; Public classBindserviceextendsService {Private Static FinalString TAG = "Bindservice"; PrivateMybinder Mybinder =NewMybinder ();  Public voidMyMethod () {log.i (TAG,"Bindservice-->mymethod ()"); } @Override Publicibinder onbind (Intent Intent) {log.i (TAG,"Bindservice-->onbind ()"); returnMybinder; }         Public classMybinderextendsbinder{ PublicBindservice GetService1 () {returnBindservice. This; }} @Override Public voidonCreate () {log.i (TAG,"Bindservice-->oncreate ()"); Super. OnCreate (); } @Override Public voidOnStart (Intent Intent,intStartid) {log.i (TAG,"Bindservice-->onstart ()"); Super. OnStart (Intent, Startid); } @Override Public voidOnDestroy () {log.i (TAG,"Bindservice-->ondestroy ()"); Super. OnDestroy (); } @Override Public BooleanOnunbind (Intent Intent) {log.i (TAG,"Bindservice-->onunbind ()"); return Super. Onunbind (Intent); }    }

The Onservicedisconnected method is only used when the service is disconnected due to an exception.

Because the OnStart () method of the service is called only when the service is started by StartService (), it is important to note this when using OnStart ().

Communicate with the Service and let it run continuously

What if we want to keep communication with the service and don't want the service to exit with the Activity? You can first StartService () and then Bindservice (). The Unbindservice () method executes when you do not need to bind, and executing this method only triggers the service's onunbind () and does not destroy the service. This allows the communication to be maintained with the Service and will not be destroyed as the Activity is destroyed.

Of course the proposed method is to make the service into a front-office operation, we just need to call Startforeground inside the Onstartcommand, and then OnDestroy inside call Stopforeground can

Intent i =NewIntent (); I.setclassname (Getapplicationcontext (),"Com.activity.MyActivity"); //Note the FLAG setting for intent: Flag_activity_clear_top://If the activity is already running in the current task, the activity at its front end will be closed, and it will be the most front-end activity. Flag_activity_single_top://If the activity is already running at the front end, no reload is required. Setting these two flags allows one and only one activity (the service interface) to run at the forefront. I.setflags (Intent.flag_activity_clear_top|intent.flag_activity_single_top); Pendingintent Pi= Pendingintent.getactivity ( This, 0, I, 0); Notification mynotify=NewNotification.builder ( This). Setsmallicon (R.drawable.logo). Setcontenttitle ("My Software"). Setcontenttext ("Running"). Setcontentintent (PI). GetNotification (); //setting the flag for notification indicates that the notification does not disappear after clicking the notification, and the icon is still displayed in the notification bar on the right-most image. This is to ensure that after exiting the activity, the status bar still has the icon to pull down, click and re-enter the activity. Mynotify.flags |=notification.flag_no_clear; //step 2:startforeground (int,//Notification) Sets the service to the foreground state so that the system knows that the service is the user's concern, low memory is not killed, and provides notification to the user that the foreground state is in progress. Startforeground (12345, mynotify);

Android Service startup mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.