Service of Android four components

Source: Internet
Author: User

Two ways to open the service of Android four components:
    1. StartService (); Turn on the service.
      After the service is turned on, the service will run in the background for a long time, even if the caller exits. The service continues to run in the background. The service is not related to the caller, and the caller is not allowed to access the method inside the service.
    2. Bindservice (); Bind service.
      When the service is turned on, the life cycle is associated with the caller. The caller hangs up and the service hangs up. Not to be born at the same time, but to die at the same time. The caller and the service are bound together, and callers can indirectly invoke methods inside the service.

Local Service: Service code in this application
Remote service: The service is inside another application (another process inside)
Aidl:android Interface Defination Language
IPC Implementation:inter Process Communication

The life cycle of a service mix call

After you turn on the service and then go to bind the service and then stop the service, the service cannot be stopped. You must first unbind the service and then stop the service, which is often used in real-world development.
Turn on the service (ensure the service is running in the background) –> Bind service (method of invoking service) –> Unbind Service (service continues to run in the background) –> stop service (service stop), service will only be opened once,
If it is turned on, then it is not effective to perform the open operation.

The principle of the binding service invocation method
  1. Define an interface that defines a method

    publicinterface IService {    publicvoidcallMethodInService();//通过该类中提供一个方法,让自定 义的类实现这个接口}
  2. Customize a IBinder implementation class in the service so that the class inherits the binder (Binder is the default adapter for IBinder), because this custom class is private, and for other classes to get the class,
    We're going to define an interface that provides a way for the IBinder class to implement the interface and invoke the method in the appropriate method for others to invoke.

     Public  class testservice extends Service {    @Override     PublicIBinderOnbind(Intent Intent) {System.out.println ("Onbind");return NewMybinder (); }Private  class mybinder extends Binder implements IService{          Public void Callmethodinservice(){//Implement the method to invoke the method in the serviceMethodinservice (); }    }//methods in the service     Public void Methodinservice() {Toast.maketext ( This,"I am the service inside the spring elder brother, Barabula!",0). Show (); }}
  3. The invocation class of the service onServiceConnected strongly turns the second argument in the method into an interface

     Public  class demoactivity extends Activity {    PrivateIntent Intent;PrivateMyConn Conn;PrivateIService IService;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Intent =NewIntent ( This, Testservice.class);    Setcontentview (R.layout.main); } Public void Start(View view)    {StartService (intent); } Public void Stop(View view)    {StopService (intent); } Public void Bind(View view) {conn =NewMyConn ();//1. The binding service passes a Conn object. This conn is a callback interface.Bindservice (Intent, Conn, context.bind_auto_create); } Public void Unbind(View view)    {Unbindservice (conn); }//Invoke methods in the service     Public void Pager(View view)    {Iservice.callmethodinservice (); }Private  class myconn implements serviceconnection{        //method that is called when the service is successfully bound.        @Override         Public void onserviceconnected(componentname name, IBinder service) {//The second parameter is the return value of the Onbind method in the serviceIService = (iservice) service; }@Override         Public void onservicedisconnected(componentname name) {        }    }}
Remote Service Aidl

The principle of the method in the binding service invocation service is described above, as is the binding for remote services.
But this remote service is in another program, the interface defined in another program,
Not in another program, even if we define an exact same in our own application.
interface, but due to the different registration of the two programs, the two interfaces are not the same, in order to solve this
Problem, Google's engineers gave the aidl, and we will define this interface to .java change .aidl ,
Then remove all of this interface 权限修饰符 and copy the Aidl in another program.
In the same package name, because the Android application is distinguished by the package name, the two
aidlPackage name, the system considers the interface in both programs to be the same, so that it can be in another
A program to turn the parameters into this interface, after the use aidl of files copied to their own project will automatically
Generates an interface class that has an inner class that Stub inherits Binder and implements the
This interface, so we IBinder的实现类 only need to let the custom class inherit Stub类 when customizing

  1. Define an interface in the remote service and change it toaidl

    package com.seal.test.service;interface IService {     void callMethodInService();}
  2. Define one in the remote service Ibinder的实现类 , let the implementation class inherit the above interface Stub类 ,
    and onBind return this custom class object in the method

     Public  class remoteservice extends Service {    @Override     PublicIBinderOnbind(Intent Intent) {System.out.println ("Remote service is bound");return NewMybinder (); }Private  class mybinder extends iservice. Stub {        @Override         Public void Callmethodinservice() {methodinservice (); }    } Public void Methodinservice() {System.out.println ("I'm the method inside the remote service."); }}
  3. In other programs, when you want to bind the service and call the methods in this service, first copy
    This aidl file into your own project, and then ServiceConnection the implementation class will make this parameter
    asInterfaceby means of a method, the interface is then obtained, and the method in the interface is called.

     Public  class callremoteactivity extends Activity {    PrivateIntent Service;PrivateIService IService;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main); Service =NewIntent (); Service.setaction ("Com.itheima.xxxx"); } Public void Bind(View veiw) {Bindservice (service,NewMyConn (), bind_auto_create); } Public void Pager(View view) {Try{Iservice.callmethodinservice (); }Catch(RemoteException e)        {E.printstacktrace (); }    }Private  class myconn implements serviceconnection{        @Override         Public void onserviceconnected(componentname name, IBinder service)        {IService = IService.Stub.asInterface (service); }@Override         Public void onservicedisconnected(componentname name) {//TODO auto-generated method stub}    }}

Finally, say IntentService :

IntentServiceis a Service subclass that is used to handle asynchronous requests. The client can pass startService(Intent) the requested delivery request by means of a method Intent IntentService ,
IntentServicewill be Intent added to the queue, then each one Intent is opened for worker thread processing, after all the work is done automatically stop Service .
Each request is processed in a separate worker thread process and does not block the main thread of the application. In fact, a IntentService Looper Handler Service Collection of, and,
He not only has the function of service, but also the function of processing and looping messages.

    • Service:
      1. A Service is a separate process. The Service object itself does not imply it was running in its own process; Unless otherwise specified,
        It runs in the same process as the application it was part of.
      2. A Service is not a thread. It is a means itself to does work off of the main thread (to avoid application not responding errors).
        Therefore, Service a new thread must be opened in the time-consuming operation.

As for why to useServiceInstead ofThread, the main difference is that the life cycle is different,Serviceis a component of the Android system, the Android system will try to keepServiceThe long-run background,
Even if memory is not enough to kill the service (which rarely occurs when there is less memory to kill the service), the service will be resurrected when the memory is available, andThreadThen they'll be killed.
1. Intentservice is a base class for Services, handle asynchronous requests (expressed as Intents) on demand.
Clients send requests Throughstartservice (Intent) calls;
The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of Work.
2. This "Work Queue processor" pattern was commonly used to offload the tasks from a application ' s main thread.
The Intentservice class exists to simplify this pattern and take care of the mechanics.
To use it, extend Intentservice and implement Onhandleintent (Intent). Intentservice would receive the Intents, launch a worker thread,
and stop the service as appropriate.
3. All requests is handled on a single worker Thread–they could take as long as necessary (and would not block the Applica tion ' s main loop),
But only one request is processed at a time.

    • Email: [Email protected]
    • Good luck!

Service of Android four components

Related Article

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: 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.