Service of Android four components

Source: Internet
Author: User

---restore content starts---

The life cycle of 1,service

OnCreate is called when the service is created for the first time.

Onstartcommand is called when the service is started.

OnStart (Thismethod is deprecated in API level 5. Implement onStartCommand(Intent, int, int) instead. )

Called when the OnDestroy is destroyed.

2, Process priority (high-to-low): (Two processes in red font are two processes that are often recycled by the system)
1. Foreground the process of the application that the foreground process user is manipulating.

2. Visible process The process that the user can see, but cannot manipulate the application.

3. The process in which the service process service processes the services running in the background. (If there is activity to the foreground, the process belongs to the foreground process)

4. Background Process Daemon To minimize the application, managed to run in the background .

5. empty process has exited the program, no task is running .

3,service Precautions for use:

1. Can I write some time-consuming actions in the service? No. If there is a time-consuming operation it may cause the ANR to occur. (Is it possible to write time-consuming operations within the OnReceive method?) Reason
The reason is that the code for the service callback methods is running on the main thread.

2.IntentService The service has started a thread and you no longer have to boot. What you have to do is write directly to Onhandleintent, which will be processed in the thread of the Strand.

Three-way interview questions:

    1. The difference between service and activity.
      • Activity can interact with the user, and the service can do things in the background without interacting with the user.
      • The activity exits after exiting the program, and for the service, if no call is stopped, the service does not end and it is still running in the background.
      • The biggest difference should be: a background process without a service run is called a background process, and a daemon that has a service is called a service process. The memory recovery of an Android system often reclaims low-priority background processes.
    2. Why do I keep the empty process now that the program has exited?
      • Optimize the user experience. The next time the user launches the app, there is no need to re-assign the process, saving time and improving efficiency. Recycle resources are only available when memory is low. 
    3. Service and threads are running in the background, what's the relationship between them?
      • Service and thread are not a category of things. Service is one of the four components and is a special class that can be used in a service for another thread. The service itself is not running in a separate process, and the service is running in the main thread by default.

Specific use of service:

    1. Start service and stop service in activity

  

1 // Start the service 2 New Intent (This, MyService.  Class); 3 StartService (intent); 4 // Stop Service 5 New Intent (This, MyService.  Class); 6 StopService (intent);

2,activity by binding the service, you can invoke the methods within the services (if the activity is closed, the service will also end)

//methods in the activity that invoke the local service (a service in the same app)://1. Call Bindservice to bind the service, passing a connection bridge object//2. Within the service to inherit a binder, implement the subclass. The subclass is free to invoke the party within the service//law. //3. In the Onbind method, returns the implementation of the subclass. //4. When the binding is OK and the connection bridge is successful, the onserviceconnected of the bridge object is called, which returns a IBinder object, which is the one returned by Onbind. //5. After getting this IBinder object, strong to Mybinder receive, then call its method. //binding and reconciling services Public voidbindservice (view view) {//Binding ServiceIntent Intent =NewIntent ( This, MyService.class); Myserviceconnection=Newmyserviceconnection ();    Bindservice (Intent, myserviceconnection, bind_auto_create); }     Public voidunbindservice (view view) {//Unbind Service        if(myserviceconnection!=NULL) {unbindservice (myserviceconnection); }    }     Public voidcalllocalservicemetod (view view) {//Calling Local methods        if(binder!=NULL) {log.i ("MyService", "calling local method"); FinalString Callparentmethod =Binder.callparentmethod (); Final intCount =Binder.getcount (); Toast.maketext ( This, callparentmethod+count,toast.length_short). Show (); }    }    classMyserviceconnectionImplementsserviceconnection{//call when the service is set up@Override Public voidonserviceconnected (componentname name, IBinder service) {if(service!=NULL) {Binder=(myservice.mybinder) service; } log.i ("Myserviceconnection", "onserviceconnected"); }        //called when the service connection is broken//onservicedisconnected () is not called when the connection is closed properly, and the method is only invoked when the service is destroyed or killed. //For example, there is insufficient system resources to close some services,//The Service that is just connected to the binding is one of the closed, and this time onservicedisconnected () is called. @Override Public voidonservicedisconnected (componentname name) {LOG.I ("Myserviceconnection", "onservicedisconnected"); }    }//Service Method Public classMyServiceextendsService { Public intcount;  Public Booleanflag=true;  PublicMyService () {} PublicString GetName () {return"I am MyService"; }    classMybinderextendsbinder{//Binder is used to transfer data.         PublicString Callparentmethod () {returnGetName (); }         Public intGetCount () {returncount; }} @Override Publicibinder onbind (Intent Intent) {log.i ("MyService", "OnCreate"); NewThread () {@Override Public voidrun () {Super. Run (); //start doing services on a binding                 while(flag) {count++; Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } log.i ("Started with a bound service", "" +count);        }}}.start (); //Call local Method Yes return value        return NewMybinder (); //} @Override Public voidonCreate () {Super. OnCreate (); LOG.I ("MyService", "OnCreate"); } @Override Public voidOnDestroy () {Super. OnDestroy (); LOG.I ("MyService", "OnDestroy"); Flag=false; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.I ("MyService", "Onstartcommand"); return Super. Onstartcommand (Intent, flags, Startid); }}

3, interprocess communication (IPC) (Android uses an interface Definition language aidl (Android Interface definition Language) to expose the service interface in a way that exposes the service interfaces)

interprocess Communication Implementation process:1. Define the service class.2. Define the Aidl interface file.3The object that implements the Aidl interface stub is returned in the Onbind method in the service.4. In another program, call the Bindservice method to bind the service.5. Copy the Aidl interface file (including the package name) into another program.6The IBinder object is converted to a Aidl interface object in the Onserviceconnected method.7. Invoke methods using interface objects (this is called to the remote Service's method to implement interprocess communication)//The remote service being invoked//Interface PackageCom.rgd.day16_bindservice;//Declare any non-default types here with import statementsInterfacemyaidlinterface {String callparentmethod (); intGetCount ();}//the remote service to writeclassMyBinder2extendsmyaidlinterface.stub{@Override PublicString Callparentmethod ()throwsRemoteException {returnGetName (); } @Override Public intGetCount ()throwsRemoteException {returncount; }    }//locally called to write theclassMyConnectionImplementsserviceconnection{@Override Public voidonserviceconnected (componentname name, IBinder service) {if(service!=NULL) {Binder=MyAIDLInterface.Stub.asInterface (service); }} @Override Public voidonservicedisconnected (componentname name) {}} Public voidbindremoteservice (view view) {//Binding Remote ServicesIntent Intent =NewIntent (); Intent.setaction ("Com.ren.myservice"); Intent.setpackage ("Com.rgd.day16_bindservice"); MyConnection=Newmyconnection ();    Bindservice (Intent, myconnection,bind_auto_create); }     Public voidunbindremoteservice (view view) {//Unbind a remote service        if(myconnection!=NULL) {unbindservice (myconnection); }    }     Public voidcallremoteservicemetod (view view) {//methods for invoking remote services        if(binder!=NULL){            Try{String s=Binder.callparentmethod (); intGetCount =Binder.getcount (); Toast.maketext ( This, s+getcount,toast.length_short). Show (); } Catch(RemoteException e) {e.printstacktrace (); }        }    }

               

Service of Android four components

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.