service of android's four components

Keywords: Java Android

                    catalogue

         I. concept of service

        II. Creation method of service

                < 1> Specific steps for service creation

                < 2> Specific instance of service creation

          III. service startup mode and life cycle method under corresponding startup mode

                < 1> Unbound
                           < 1.1 > specific ways to start services unbound
                           < 1.2 > if the Service is started unbound, the corresponding life cycle method of the Service and the level of the process in which the Service is located
                            < 1.3 > the purpose of using unbound startup service
                 < 2> Binding type
                             < 2.1 > specific ways to start services by binding
                              < 2.2 > binding startup Service, corresponding to the Service life cycle and Service location                                          The level of the process
                              < 2.3 > purpose of using binding to start service
                  < 3> Hybrid
                               < 3.1 > specific ways of hybrid startup service
                               < 3.2 > the life cycle of the service after hybrid startup and the level of the process in which the service is located
                                < 3.3 > purpose of using hybrid startup service

          IV. communication between service and activity

                 < 1> Overview of communication between services and activities    
                 < 2> General version of communication between service and activity
                                < 2.1 > general description of the process of realizing communication between service and activity
                                < 2.2 > specific code examples
                < 3> Improved version of communication between service and activity (added interface)
                                < 3.1 > reason description of code improvement
                                < 3.2 > improved code   
                 < 4> The essence of communication between services and activities (that is, the essence of starting services by binding, so that activities and services can communicate)

            V. start remote service

                      5.1 what is remote service? What is a local service?
                      5.2 what is the difference between starting a remote service and starting a local service?
                      5.3 the essence of starting remote services (bound and unbound) and why use aidl?
                      5.4 code example of starting remote service

            AIDL for interprocess communication

                       6.1 common methods for creating aidl (also available in android studio):
                       6.2 creating aidl in android studio
                       6.3 after creating the aidl file, start the remote service to realize the code change of activity and its communication
                                        < 1> After creating the aidl, the code for starting the remote service changes
                                        < 2> Create aidl and start all code instances of remote service (remote certificate processing)

              VII. Priority of process

              Eight points for attention

I. concept of service

I. concept of service

       Service yes android One of the four components, the component running in the background, has no foreground interface, and is used to run the code that needs to be executed in the background.
       Service and activity You need to register in the manifest file to use it.
       Service It can be started by display or hermit. For display startup, the configuration intent-filter It's useless. Only the hermit starts server It will only be useful at this time.
       Service yes context A subclass of, activity Also context Subclass of, but BroadCastReceiver no context Subclass of.
       Create a class A inherit Service,android There is only one class in the system A The object will not be created repeatedly because Servic Not by new Come out, through Intent To start, and this action is created by android What the system does is not what we do with code.

II. Creation method of service

           < 1> Specific steps for service creation

 <1.1>Create a class inheritance Service,Override its lifecycle method oncreate(),onBind(),onUnbind(),onstartCommand(),onDestroy()
 <1.2>Register in the manifest file. The root node is service

           < 2> Specific instance of service creation

			<2.1>Create a class inheritance Service

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("onBind");
		return null;
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("onUnbind");
		return super.onUnbind(intent);
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("onCreate");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("onDestroy");
	}

}

		<2>Register in manifest file
       <service android:name="com.itheima.runservice.MyService"></service> 

III. service startup mode and life cycle method under corresponding startup mode

              There are two ways to start a service. The first is to call unbound, the second is bound, and the third is hybrid. However, whether bound or unbound, the service is started through Intent.

              < 1> Unbound

                      < 1.1 > specific ways to start services unbound

				1>Method used:
                		startService(Intent intent):Start service
                        stopService(Intent intent);Shut down service

				2>The code is as follows:

					public void start(View v){
    						Intent intent = new Intent(this, MyService.class);
    						startService(intent);
    				}
    				public void stop(View v){
    						Intent intent = new Intent(this, MyService.class);
    						stopService(intent);
 				   }

                        < 1.2 > if the Service is started unbound, the corresponding life cycle method of the Service and the level of the process in which the Service is located

				1>The lifecycle approach at this point is oncreate()------onStartCommand()-----onDestroy(),Repeat call startService(),At this time, the system will continue to repeat onStartCommand() Method, and repeated stopService()Will do nothing., Actually service Service The life cycle approaches are onStart(),But now it has been abandoned and used onStartCommand()To replace onStart()There's no way.
                2>At this time, the process where the service is located becomes a service process (once the service is started, when the service is started activity After death, the service will still exist).

                         < 1.3 > the purpose of using unbound startup service

				In order to turn the process where the service is located into a service process, the priority of the process is increased.

              < 2> Binding type

                    < 2.1 > specific ways to start services by binding

			1>The method used to start the service by binding:
            		//The first parameter: Intent type, which starts the service through Intent
                    //The second parameter: the subclass object of ServiceConnection, through which the activity accesses the methods in the service
                    //The third parameter: the creation method of the service, which is generally BIND_AUTO_CREATE
					bindService(intent, conn, BIND_AUTO_CREATE);
					//First parameter: subclass object of ServiceConnection
					unbindService(conn);
				When we want to open and close a service, the above two methods ServiceConneciton Subclass objects must be the same.
                
            2>Specific code of bound startup service:

public void bind(View v){
    	Intent intent = new Intent(this, MyService.class);
    	bindService(intent, conn, BIND_AUTO_CREATE);//Binding service
    }
   
    public void unbind(View v){
    	unbindService(conn);//Unbinding service
    }

//These are the main parameters:
private MyServiceConn conn;
class MyServiceConn implements ServiceConnection{


		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			
		}

	
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
    	
    }

                      < 2.2 > binding startup Service, corresponding to the Service life cycle and the level of the process in which the Service is located

			1>The lifecycle approach at this point is oncreate()---onBind()------onUnbind()----onDestroy(),At this point, duplicate binding services (i.e., duplicate calls bindService()Method binding service). At this time, the system does nothing and will not go again oncreate()and onBind()method; The unbinding service (i.e. repeated calls) is repeated at that time unbinderService()To unbind the service), and the system will crash (because the service has been unbound, and then unbind the service again. At this time, the service is an unbound service, so the program will crash)
            2>The process in which the service is located will not become a service process (once the service is bound, when the action of binding the service is executed activity If it dies, the service will execute automatically and directly onUnbinder()--onDestroy()Method, that is, the service is directly unbound and destroyed; but when the service is executed unbindService()After the code is unbound, this activity Can exist). At this time, the process in which the service is located is what process it should be.

                         < 2.3 > purpose of using binding to start service

			To make activity Can access service Method in, by Ibinder This middleman.

            < 3> Hybrid

                       < 3.1 > specific ways of hybrid startup service

			<1>In fact, both methods are used. The code is as follows:

private MyServiceConn conn= new MyServiceConn();


 public void start(View v){
    	Intent intent = new Intent(this, MyService.class);
    	startService(intent);
    }
    public void stop(View v){
    	Intent intent = new Intent(this, MyService.class);
    	stopService(intent);
    }
    
    public void bind(View v){
    	Intent intent = new Intent(this, MyService.class);
    	bindService(intent, conn, BIND_AUTO_CREATE);
    }
   
    public void unbind(View v){
    	unbindService(conn);
    }
    private MyServiceConn conn;
    class MyServiceConn implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
    }

                        < 3.2 > the life cycle of the service after hybrid startup and the level of the process in which the service is located

			<1>The methods called in sequence for hybrid startup are: startService()--->bindService()->unbindService()-->stopServer(),Pay attention to this process. Generally speaking, do not change, otherwise it is easy to have problems; When performing the above method, serview The execution cycle method is as follows: (Note::The so-called hybrid start can be startService()+bindService()+unbindService(),It can also be startService()+bindService()+unbindService()+stopService(),perhaps startService()+bindService()These are the three),Using the hybrid startup service, the life cycle method of each corresponding method is as follows:
              Start in mixed mode service After that, click repeatedly startService()Method, the system will walk repeatedly onStartCommand()Cycle method: repeated clicks bindService()Method, the system will do nothing; Repeated clicks unbindService()Method, the system will crash; Repeated clicks stopService Method, the system will do nothing at this time.
            <2>Start the service in a hybrid way, and the process in which the service is located will become a service process.

                         < 3.3 > purpose of using hybrid startup service

On the one hand, it is to provide services Service The process becomes a service process, and the priority of the process is increased; The second aspect is to make activtiy Services can be invoked Service Methods in.

IV. communication between service and activity

                         < 1> Overview of communication between services and activities    

			 <1>The so-called service and activity Communication between is actually activity Calling service in Service Method in, by Ibinder This middleman.
             <2>Only services started by binding can be implemented activity Communication between and services.
             <3>Ibinder How do you act as a middleman?
             		 What is a middleman? For example, an object in two places is the same, and then the two places communicate through the same object, and the same object in two places is the intermediary, Ibinder That's it,
                     The specific embodiment in the code is: binderService The second parameter of the method( ServiceConnection Methods in subclasses (objects) onServiceConnected Second parameter of( IBinder service)and
                     Service in onbind()Method IBinder Object, this IBinder Object is the same object.     
             <4>Ibinder It is an interface, and there are many abstract methods to be implemented android One of them has been implemented Ibinder Basic class of interface Binder,So we basically use Binder To replace Ibinder

                         < 2> Communication between service and activity   General version of

                                    < 2.1 > general description of the process of realizing communication between service and activity

                      **First determine the server It is started by binding, and then called bindService(Intent intent,ServiceConnect connect ,Creation method (generally automatic creation)),An inner class is created B Class for inheritance ServiceConenction Class, there are two methods to implement onServiceConnect( IBinder ibinder),onServicedisConnect().
                       **In inheritance server Create an inner class in a subclass of A Class inheritance Binder Class( Binder Class is implementation IBinder An underlying class of the interface, and then in the inner class (i.e A Class) D Used to invoke inheritance server Methods in subclasses of.
                       **In inheritance server In subclasses of Onbinder()Method directly returns the above inner class (that is A Class).
                       **At the end of the binding service activity In, create a global variable C---A Class object, and then B Class method onServiceConect(IBinder ibinder)Formal parameters on ibinder Assign value to by strong transformation C. 
                        **At this point, you can pass through the object C To call the method D,So as to achieve call inheritance Server Methods in subclasses of.

                                    < 2.2 > specific code examples

//1 this is the code in the activity
public class Main3Activity extends AppCompatActivity {

    //Declare a global variable here (the object in the service that inherits the subclass of Binder class)
    MyServer.Renmishu mishu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        initView();
        Intent intent = new Intent(this, MyServer.class);
        bindService(intent, new MyServiceConnection(), BIND_AUTO_CREATE);
    }


    public class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //The IBinder object service here inherits the return value of the onBinder() method in the subclass of the service.
            //Turn the IBinder object service into a global variable mishu (an object in the service that inherits the subclass of Binder class) by strong conversion
            if (null == mishu) {
                mishu = (MyServer.Renmishu) service;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private void initView() {
        Button bt_banzheng = (Button) findViewById(R.id.bt_banzheng);
        bt_banzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //3. Call its method through the object here, because the object has been assigned.
                mishu.banzhengle();
            }
        });
    }
    

// 2. This is a subclass that inherits Service.
    public class MyServer extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //Return the internal class object, pass the object, and generally get the object from the activity.
        return new Renmishu();
    }


    //Binder class is a subclass that implements the IBinder interface.
    //1. Create an internal class to inherit Binder object (this is a bridge), and then create a method in this class to call the method in Myserver.
    public class Renmishu extends Binder {
        public void banzhengle() {
            banzheng();
        }
    }

    //This is the method in Myserver.
    public void banzheng() {
        Log.d("qindong", "banzheng");
    }
}

                         < 3> Communication between service and activity   Improved version of (added interface)

                                     < 3.1 > reason description of code improvement

 In succession service Some methods in subclasses of( A Method) can make activity For the visit,
 But there are some ways( B Method) is not to let activity Access, but it inherits at this time service Inner class in subclass of C class
 (Inherited Binder Class) in some need, you must create a method in this class to call B Method (do not want activity Access method),
 At this time activity You can use the method directly B Methods. To avoid this problem, the following scheme is proposed: directly create an interface and define some methods in the interface,
 Give Way C Class to implement this interface, and then we can activity The accessed methods let you write directly to the methods defined by these interfaces,
 And those who don't want activity The access method is not defined as the method of this interface; stay activity In, we don't have to create C Class object,
 Instead, an interface object is created and called through the interface object C Class.

                                     < 3.2 > improved code  

//1. Interface created
public interface BusinessInterface {
public void banzhengle();
}

//2. It inherits the subclass of Service
public class MyServer extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //Return the internal class object, pass the object, and generally get the object from the activity.
        return new Renmishu();
    }


    //Binder class is a subclass that implements the IBinder interface.
    //1. Create an internal class to inherit Binder object (this is a bridge), and then create a method in this class to call the method in Myserver.
    //Implement the business interface to distinguish the methods in MyServer that you want activity to access from those that you don't want activity to access
    //The method defined in the interface will directly call the method in MyServer that you want the activity to access
    public class Renmishu extends Binder implements BusinessInterface {

        @Override
        public void banzhengle() {
            banzheng();
        }
    }

    //This method is intended for the activity to access.
    public void banzheng() {
        Log.d("qindong", "banzheng");
    }

    //This method does not want the activity to access.
    public void yule() {
        Log.d("qindong", "Ha ha ha");
    }

}

//3.activity code
public class Main3Activity extends AppCompatActivity {

    //Declare a global variable here (the object in the service that inherits the subclass of Binder class)
    //MyServer.Renmishu mishu;
    //Replace the above object with an interface object here
    BusinessInterface mishu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        initView();
        Intent intent = new Intent(this, MyServer.class);
        bindService(intent, new MyServiceConnection(), BIND_AUTO_CREATE);
    }


    public class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //The IBinder object service here inherits the return value of the onBinder() method in the subclass of the service.
            //Turn the IBinder object service into a global variable mishu (an object in the service that inherits the subclass of Binder class) by strong conversion
            if (null == mishu) {
                //Here is polymorphism. The subclass object points to the parent class reference.
                mishu = (MyServer.Renmishu) service;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private void initView() {
        Button bt_banzheng = (Button) findViewById(R.id.bt_banzheng);
        bt_banzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //3. Call its method through the object here,
                mishu.banzhengle();
            }
        });
    }
}

                    < 4> The essence of communication between services and activities (that is, the essence of starting services by binding, so that activities and services can communicate)

				use BindService()Method to bind the service, and the method in the service will be called oncreate()and onbind()Method, when onbind()When the method has a return value, the system will call bindservice()Method in the second parameter of the method onServiceConnect(Ibind ibind),take onbind()The return value of the method is assigned to onServiceConnect(Ibind ibind)In method Ibind Object; But when onbind()When the method has no return value, the system will not call bindservice()Method in the second parameter of the method onServiceConnect(Ibind ibind)
This needs to be verified; onServiceConnect()method, onServiceDisConnect()method----Yes, the service has been bound before (i.e onbind()Method has a return value), and then it will be called only after it is unbound onServiceDisConnect()method
                            For remote services, the process is the same when onbind()When the method has a return value, the system will call onServiceConnect(Ibind ibind)Method, and onBind()The return value in the method is copied to the return value in the method Ibind Object, that is, our local activity Actually, I've got the remote service IBinder Object, but the question is, how do we deal with this IBinder Object, because it was created before business The inner classes that act as intermediaries in interfaces and services are in remote services service How do we get services from one application to another service The internal class created in and the interface defined in the project where the service is located, as a result, can not be obtained, so inter process communication should be used at this time AIDL  
                 AIDL The essence of:  
                 	There will be a file in the project where the service is located and the project where the service is started, business.aidl File, the system will aidl Files, automatically create related java File. that is buiness.java Class, at this time buiness It is also an interface. At this time, the system will connect the two interfaces business.java Is for the same class. And this buiness.java Class has a static inner class Stub Class, this Stub Class inherits Binder And interface Business,At this point, we can turn strongly and realize it actiity and service Communication (i.e actiity Can call service Method in)

V. start remote service

                5.1 what is remote service? What is a local service?

			<1>Local service: activity and service It is called a local service in the same project
            <2>Remote: actiivty and service It is not called remote service in the same project.

                5.2 what is the difference between starting a remote service and starting a local service?

<1>Different startup methods: remote services can only be started through intent The hermit intends to start, while the local service is through Intent The display intention and hermit intention can be started, but it is recommended Intent Just show your intention.
    <2>When we want to implement services and activity The process of communication is different,
    	We want to achieve service and activity To communicate between, you must start the service using binding. At this time
    		For local services, just follow the normal steps.
            For remote services, cooperation is required aidl To achieve this effect.
        At that time, when we started the remote service using unbound mode, the code for starting the local service and starting the service are the same, which can achieve the effect.

                5.3 the essence of starting remote services (bound and unbound) and why use aidl?

<1>The essence of starting a remote service using unbound methods:
        		When we use startSerice()When starting the remote service, the system will look for the parameters in the method intent Matching Intnent-filter,And the root node is service,If found, call the service of oncreate()and onStartCommand()Method, but if it is not found, then forget it and do not report exceptions; When we use stopService()When the remote service is turned off, the system still goes back to find the connection with this intent Matching intnet-filter,And the root node is service,If found, call the service of ondestroy()If the method is not found, it is OK and no exception is reported.
                
        <2>The essence of starting a remote service using binding
        		When we're in a activity use binderService()When starting the remote service, the system looks for the parameters in the method intent Matching Intent-filter,And the root node is service,If found, call the service Class oncreate()and onBind()Method, if onBind()Method has a return value, not null null,At this point, the system will the method in the remote service onbind()The return value of is assigned across processes to another application (that is activity The corresponding method of starting the service in the application) binderService()Second parameter in( ServiceConnection Methods in onServiceConnection(ComponentName name, IBinder service)Second parameter in service;If onBind()The return value of the method is null At this time, the system will not call activity Medium bindservice In the second parameter of onServiceConneciton()There's no way.
                ;When the system does not find binderService Parameters in intent Matching Intent-filter,And the root node is service of service When you are, forget it. Do nothing and report no exceptions.
                When we're in a activity use unBinderService()When closing the remote service, find the remote service first as in the above process service,Call directly after service of onUnbind()and ondestroy()method.
             Note: that is, as long as the onbind()The return value of some methods is not null At this time activity You can get the information in the remote service onbind()Method, and IBinder Cross process communication has been completed.   
        
        <3>Why use aidl?
			  First of all, when we use unbound to start a remote service, we don't need to use it aidl of Only when we start a remote service using binding or hybrid startup (using binderService()Method), which is only needed when you want to communicate with a remote service aidl.
              When we use binderService()Method to start the remote service, and the onbind()The return value of the method is not null By this time, we have got it onBind()Method, that is binderService()Second parameter in( ServiceConnection Subclass of) onServiceConnection(ComponentName name, IBinder service)Second parameter in service,At this time, the idea that we want to call the relevant methods in the remote service through this object cannot be realized. Of course, the returned object is actually the remote service Service An inner class object in that inherits binder It implements the extended interface (here it is called Business),However, polymorphism is used here, as follows
              IBinder service=Inherited in remote service IBinder,The extended interface is implemented (let's call it business)An internal class object of.
              Because parameters service yes IBinder Type, and IBinder There is no specific method we want to call in the interface. At this time, we need to perform forced conversion, but forced conversion needs the extended interface in the remote service( business)And internal class objects, otherwise how to perform forced conversion aidl It came into being.
              AIDL The essence of:  
                 	There will be a file in the project where the service is located and the project where the service is started, business.aidl File, the system will aidl Files, automatically create related java File. That is buiness.java Class, at this time buiness It is also an interface. At this time, the system will connect the two interfaces business.java Is for the same class buiness.java Class has a static inner class Stub Class, this Stub Class inherits Binder And interface Business,We can pass the Stub Class, as follows actiity and service Communication (i.e actiity Can call service Method in)
                   Bussinesss  bussinesss = Bussinesss.Stub.asInterface(service);
                   //At this point, you can call the relevant methods in the remote service through the object businessss (of course, this method needs to be defined in business)

                5.4 code example of starting remote service

//1 this is the first application where MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        Button mainactivity_bt_banzheng= (Button) findViewById(R.id.mainactivity_bt_banzheng);
        mainactivity_bt_banzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Click Remote certificate processing
                Intent intent=new Intent();
                intent.setAction("zhongguo.henan.qindong");
                bindService(intent, new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        //In fact, the system has brought the IBinder object of the remote service, but we can't handle it
                        //The output log indicates that the service is not null and is an object 					                // onServiceConnected () is also called
                        Log.d("qindong","We got a message from remote service");
                        Log.d("qindong","We got it Ibinder The object is:"+service.toString());
                        Log.d("qindong","We got it IBinder Is it null: "+(service==null));
                    }
                    @Override
                    public void onServiceDisconnected(ComponentName name) {

                    }
                },BIND_AUTO_CREATE);
            }
        });

    }
}


//2. This is the second application, which inherits the subclass BanZhengService.java of Service

public class BanZhengService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //2 return our inner class object.
        return new MyStub();
    }

    public void banzheng(){
        Log.d("qindong","I've come to apply for your certificate remotely");
    }

    //1 create an internal class to inherit Binder and implement Business interface
    public class MyStub extends Binder implements Business{

        @Override
        public void banzheng() {
            BanZhengService.this.banzheng();
        }
    }
}
//3. This is the second application. The specific interface is Business.java

public interface Business {
    void banzheng();
}

//4. This is the manifest file for the second application

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.trueregistrationoneapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".BanZhengService">
            <intent-filter>
                <action android:name="zhongguo.henan.qindong"/>
            </intent-filter>
        </service>
    </application>
</manifest>

aidl for inter process communication (i.e. communication between local activity and remote service)

                        6.1 common methods for creating aidl (also available in android studio):

 *********The project where the remote service is located
                                1.establish AIDl File, modify the suffix of the interface file that defines the middleman method aidl
                                2.aidl All methods and variables in the file and their interfaces are defaulted to public Therefore, the access modifier can no longer be defined
                                3.then sync Click on the project and let the system aidl File generates an interface file. There is a static abstract class in the interface file Stub,This is the new middleman.
                    **********activity Project
                           1.The name of the project where the remote service is located aidl Ensure that the documents are copied into the project aidl The package name is consistent, and then recompile the project, that is sync once.
                           		In the project, the so-called package name is from the directory
                                  src/main/java/After that is the package name. In two projects, you only need to ensure that it is in two projects java After that, aidl Just keep the file directory consistent.
                           2.stay onServiceConnected Method, use Stub Method of asInterface take IBinder object service Strong conversion to interface object (polymorphism is used here, that is, the parent class reference points to the child class object)

                        6.2 creating aidl in android studio

                                        < 1> This is the project to start the service. First, click the main directory to create an aidl folder, as shown in the figure

 

                                        < 2> Create an aidl file directly in the aidl folder, create a new aidl file in the aidl folder, and then directly delete all the classes in the file, and directly copy the contents of the interface in the written aidl file, as shown in the figure:

 

 

                                         < 3> After the Aidl file is written, to sync the project, click the button as shown in the figure:

 

                                         < 4> The next step is to process the aidl file of the project where the remote service is located. First, create an aidl folder in the project where the remote service is located, as in step 1.

 

                                        < 5> Enter the aidl folder in the project where the service is started, directly copy the com package we need to the aidl folder of the project where the remote service is located, and then recompile the project where the following service is located, as shown in the figure

 

 

 

                                        < 6> The final result is as follows:

 

 

                        6.3 after creating the aidl file, start the remote service to realize the code change of activity and its communication

                                < 1> After creating the aidl, the code for starting the remote service changes

		When in activity Both the project and the remote service project already exist aidl The file is, and the code is modified as follows:
        <1>For remote services, the original internal class inherits Binder Implementation interface Business,Now the inner class inherits directly Business In the interface Stub Class.
        <2>about activity For the application that starts the service, binderService Method in the second parameter of onServiceConnection(ComponentName name, IBinder service)In, use Stub Method of asInterface take IBinder Object is forced to become a man in the middle interface Business So that we can call the remote service service The inner class in implements the method of the interface.

            //Polymorphism is used here, that is, the parent class reference points to the child class object.
            business = Businesss.Stub.asInterface(service);

                                < 2> Create aidl and start all code instances of remote service (remote certificate processing)

//1. This is the remote Service in the second project

public class RemoteOneService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("qindong", "onBind");
        return new zhongjianren();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("qindong", "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        Log.d("qindong", "onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("qindong", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d("qindong", "onDestroy");
        super.onDestroy();
    }

    //In the interface file generated by the aidl file, the Stub is a static abstract class that inherits the Binder class and implements the business interface,
    //So just inherit Stub directly here.
    public class zhongjianren extends Businesss.Stub{
        public void zhaorenbanzhang() {
            banzheng();
        }
    }
    //Remote certificate processing
    public void banzheng(){
        Log.d("qindong","Director Wu has come to help you with your certificate!");
        System.out.print("Director Wu came to help you with your certificate");
    }
}

//2. This is the activity in the first project

public class ServiceOneActivity extends Activity {

    private MyServiceConnection myServiceConnection = new MyServiceConnection();
    private Businesss business;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_one);
        initView();
    }

    private void initView() {
        Button bt_start_service = (Button) findViewById(R.id.start_service);
        Button bt_bind_service = (Button) findViewById(R.id.bind_service);
        Button bt_unbind_service = (Button) findViewById(R.id.unbind_service);
        Button bt_stop_service = (Button) findViewById(R.id.stop_service);
        Button bt_banzheng = (Button) findViewById(R.id.bt_banzheng);

        bt_bind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Binding a remote service using an implicit diagram
                Intent intent = new Intent("henan.sanmenxia.shanxian");
                intent.setDataAndType(Uri.parse("nishi:"), "text/name");
                bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
            }
        });
        bt_unbind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Unbind remote service
                unbindService(myServiceConnection);
            }
        });
        bt_banzheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //Remote certificate processing (there will be an exception when calling the method in the remote service. Here, you can directly carry out trycach.)
                //In the interface file generated by the aidl file, the remote method throws an exception. Here, just catch it directly.
                try {
                    business.zhaorenbanzhang();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //Use the method asInterface of Stub to force the IBinder object into a subclass object of the man in the middle interface.
            //Polymorphism is used here, that is, the parent class reference points to the child class object.
            business = Businesss.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}

7, Priority of process:

####foreground Process: it has the highest priority and will not be killed. If it is killed, it will be restarted when there is enough memory.

        1. The process has an activity that can be interacted with the user (onresume () method is called)

          2. The process has a broadcast receiver that is executing the onreceive () method.

        3. The process has a server that only executes the callback method of the life cycle method oncreate ondestroy onstartCommand() (briefly raise the process level to ensure that the method is completed)

        4. Have a "running in the foreground" Service - the Service's startforegroup() call (raise the process level to ensure that the process's things are executed) (used to ensure that the Service content must be executed. You can directly call the above methods in the subclass of the inherited Service, and then call stopforegroup() after the content is executed) Method to stop using the server as a foreground process and return to its original appearance)

        5. The process has a service process bound to the foreground activity. (for remote services, when a remote service is bound to a foreground activity, the remote service is a foreground process.)

####Available process: (the process will not be killed until it is absolutely necessary; if it is killed, the process will be restarted when there is enough memory)

          1. The process has an activity(onpause () method execution) that is no longer in the foreground but is still visible to the user

            2. The process has a service bound to the visible activity (this means that the remote service is a service process.)

####server process: the process will not be killed unless it is absolutely necessary; if it is killed, the process will be restarted when there is enough memory

          1. When a service started by the startService method is running in the process (so the service is generally used when downloading files)

####Background process: it is easy to kill and will not restart

        1. Have an invisible activity (onstop method execution)

        2. When the process has a service that binds an activity that is invisible, and the activity does not call the unbind() method, the process in which the service is located is a background process.

                For example, when the app has only one page, press the home key, and the app process is a background process.

####Empty process: it's easy to kill and won't restart

        1. There are no application components (activation and service) with task activity in the process

                For example, when the app is followed by a page, and then press the return key to destroy the activity, then the process of the app is an empty process.

Eight points for attention:

                8.1 precautions for starting the service using hermit startup mode

Android 5.0 yes Service Intent The invocation policy of has changed and must be displayed Intent To start Service,If you want a hermit intent start-up Service,The following needs to be done:
Intent intent = new Intent();
intent.setAction("To start servcie It is configured in the manifest file action");
intent.setPackage("To start service Package name of the project");
context.startService(intent);

Posted by stevegg1965 on Mon, 01 Nov 2021 15:53:52 -0700