Service first experience
Introduction to this section
Okay, we have studied and studied Activity in Android in the first three sections. I believe everyone has benefited a lot! At the beginning of this section, we continue to learn the second component in Android: Service (Service), Okay, without further ado, let’s start this section!
1. Concepts related to threads
Before we start learning Service, let’s first understand some concepts of threads!
1) Related concepts:
- Program: Written in a certain language in order to complete a specific task A set of instructions (a set of static codes)
- Process:A running program, a# for system scheduling and resource allocation ##Independent unit, the operating system will Allocate a memory space for each process! The program is dynamically executed sequentially, experiencing the loading and execution of the code, Complete process executed!
- Thread: An execution unit smaller than a process. Each process may have multiple threads. Threads need to be placed in a process To execute, the thread is managed by the program , and the process is scheduled by the system !
- Understanding of multi-threading: Parallel Execute multiple instructions and allocate CPU time slices to each according to the scheduling algorithm Threads are actually executed in time-sharing, but the switching time is very short, and the user feels "at the same time"!
2) Thread life cycle:
3 ) Three ways to create a thread:
- Inherit the Thread class
- Implement the Runnable interface
- Implementing the Callable interfaceIf you are using the thread created by 2, you can start it directly like this:
new Thread(myThread).start();. More often, we like to use anonymous classes, which is written in the following way:new Thread(new Runnable(){ public void run(); }).start();
2. The difference between Service and Thread
In fact, there is not much relationship between them, but many friends often confuse these two. Got it! Thread is a thread, the smallest unit of program execution, and the basic unit of CPU allocation! Service is a component provided by Android that allows it to stay in the background for a long time. The most common The usage is to do polling operation! Or you want to do something in the background, such as downloading updates in the background! Remember not to confuse these two concepts!
3.Service life cycle diagram
4.Life cycle analysisOkay , from the life cycle in the above figure, we can know that there are two ways to use Service in Android:
1) StartService() starts Service
2)BindService() starts Service
PS: There is another way, after starting Service, bind Order Service!
1) Detailed explanation of related methods:
- onCreate(): Callback immediately after the Service is created for the first time This method, this method throughout the life cycle will only be called in order!
- onDestory(): This method will be called back when the Service is closed. This method will only be called back once!
- onStartCommand(intent,flag,startId): The early version is onStart(intent,startId), When the client calls the startService(Intent) method, it will be called back. The StartService method can be called multiple times. But no new Service object will be created, but the previously generated Service object will continue to be reused, but callbacks will continue. onStartCommand() method!
- IBinder onOnbind(intent): This method is a method that must be implemented by Service. This method will return a IBinder object, the app communicates with the Service component through this object!
- onUnbind(intent): This method will be called back when all clients bound to the Service are disconnected!
2) StartService starts Service
①The first startup will create a Service instance, and call onCreate() and onStartCommand() method, Service at this time Entering the running state, if StartService is called again to start the Service, no new Service object will be created. The system will directly reuse the previously created Service object and call its onStartCommand() method!
②But such a Service has no necessary connection with its caller. That is to say, when the caller ends its life cycle, But as long as stopService is not called, the Service will continue to run!
③No matter how many times the Service is started, you only need to call StopService once to stop the Service
3) BindService starts Service
①When bindService is used for the first time to bind a Service, the system will instantiate a Service instance and call Its onCreate() and onBind() methods, and then the caller can interact with the Service through IBinder. If bindService is used again to bind the Service, the system will not create a new Service instance, nor will the onBind() method be called again. , will only pass the IBinder object directly to other clients added later!
②If we unbind the service, we only need to call unbindService(), at which time the onUnbind and onDestory methods will Called! This is a client situation. If multiple clients are bound to the same Service, the situation is as follows When a client completes interaction with the service, it calls the unbindService() method to unbind. When all clients are unbound from the service, the system will destroy the service. (Unless the service is also started by the startService() method)
③In addition, unlike the above situation, the Service in bindService mode is related to the caller, which can be understood as "Grasshoppers on a rope", they want to die together. After bindService, once the caller is destroyed, the Service will be terminated immediately!
Analysis of bindService of Context called when calling Service through BindServicebindService (Intent Service, ServiceConnection conn, int flags)
service: Specify the Service to be started through this intent
conn: ServiceConnection object, the user monitors the relationship between the visitor and the Service connection status, The onServiceConnected(ComponentName,IBinder) method in the object is called back when the connection is successful; If the host where the Service is located terminates due to abnormal termination or other reasons, the Service will be disconnected from the visitor. Calling the onServiceDisconnected(CompanentName) method when connecting, actively disconnecting through the unBindService() method will not call the above method!
flags: Specify whether to automatically create Service when binding (if the Service has not been created yet), Parameters can be 0 (no automatic creation), BIND_AUTO_CREATE (automatic creation)
4) After StartService starts the Service, bindService is bound
If the Service has been started by a client through StartService(), then other clients will Then call bindService() to bind to the Service, then call unbindService() to unbind and finally If bindService() is called to bind to Service, the life cycle methods triggered at this time are as follows:
onCreate( )->onStartCommand( )->onBind( )->onUnbind( )-> onRebind( )
PS:The premise is: the onUnbind() method returns true!!! Some readers may have doubts here. Shouldn't Service be called after calling unbindService? onDistory() method! In fact, this is because this Service is started by our StartService , so if you call the onUnbind() method to unbind, the Service will not be terminated!
Conclusion: If we use bindService to bind a started Service, note that it has already been started. Service!!! The system only passes the internal IBinder object of the Service to the Activity and does not transfer the life cycle of the Service. It is bound to Activity, so when the unBindService() method is called to unbind, the Service will not be destroyed!
5. Life cycle verification
Next we write code to verify the life cycle:
1) Verify the calling sequence of StartService to start Service
First we customize a Service, rewrite the relevant methods, and the user prints verification on logcat:
TestService1.java
private final String TAG = "TestService1";
//Methods that must be implemented
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind method is called!");
return null;
‐‑ ‐ using void onCreate () {
Log.i (tag, "Oncreate method is called!"); ## vOncreate ();
}
#// service ## @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand method was called!");
return super.onStartCommand(intent, flags , startId);
}
Callback ");
super.onDestroy();
}
}
AndroidManifest.xml completes Service registration
<service android:name=".TestService1">
# The layout file, two buttons, and finally the writing of MainActivity, calling startService( ) and stopService( ) respectively in the click event of the button!
public class MainActivity extends Activity {
private Button start;
private Button stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R .layout.activity_main)
Start = (Button) FindViewByid (R.id.bTNSTART);
Stop = (Button) FindViewByid (R.id.btnstop);
// Create the initial of the service, and Intent attribute
final Intent intent = new Intent();
intent.setAction("com.jay.example.service.TEST_SERVICE1");
//Set click events for two buttons, respectively Start and stop service start. Service(intent);
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(intent);
}
});
}
}
Run screenshot:
##Click to start service:
##I have nothing to do after I’m full, so I’ll order a few more:
Last click to stop the service:
Result analysis:
From the above running results we can verify what is explained in our life cycle diagram: We found that the onBind() method was not called. In addition, clicking to start the Service multiple times would only call onStartCommand repeatedly. Method! No matter how many times we start the Service, a stopService will stop the Service!
2) Verify the order in which BindService starts the Service:Before we start writing code, we must first Let’s learn a few things first: The first is the bindService method of Context given below the first big picture:
ServiceConnection object: monitors the connection between the visitor and the Service. If the connection is successful, callback onServiceConnected(), if abnormal termination or other reasons cause the Service to be disconnected from the visitor When connected, the onServiceDisconnected method is called back. Calling unBindService() will not call this method!Summary:
- There is an IBinder object in the onServiceConnected method, which can implement the bound Service communication between each other! When we develop the Service class, we need to implement the IBinder onBind() method by default, which returns The IBinder object will be passed to the onServiceConnected parameter in the ServiceConnection object, and we can Communicate with the Service through this IBinder here!
Step 1:
Inherit Binder in the custom Service , implement your own IBinder objectStep 2:
Return your own IBinder object through the onBind() methodStep 3:
Define one in the class that binds the Service ServiceConnection object, override two methods,
onServiceConnected and onDisconnected! Then just read the parameters passed by IBinder directly!Okay, the next step is to write the code to verify. Here we define a Service for timing,
Then let’s demonstrate the usage of BindService and the method calling process! The code is relatively simple and I won’t explain it!
Register the Service component in AndroidManifest.xml: MainActivity.java: # #Continue to click lock: no change ##Get the status of the current Service: Unbind: If we bind again If you close the Activity directly after setting, an error will be reported.
Then the onUnbind and onDestory methods will be called automatically! From the above running results, it is verified that in the life cycle diagram:
private final String TAG = "TestService2";
private int count;
private boolean quit;
//Define onBinder method Returned object private MyBinder binder = new MyBinder();
public class MyBinder extends Binder
{
public int getCount()
{
return count;
} }
onBind method is called!");
return binder;
}
//Callback when Service is created
@Override
public void onCreate() {
super. onCreate();
Log.i(TAG, "onCreate method is called!");
//Create a thread to dynamically modify the value of count
new Thread()
{
public void run()
{
Thread.sleep(1000);
;
}
// Callback when the Service disconnects
@Override
Called!");
return true;
}
//Callback before Service is closed
@Override
public void onDestroy() {
super.onDestroy( );
this.quit = true;
Log.i(TAG, "onDestroyed method was called!");
}
@Override
public void onRebind(Intent intent ) {
Log.i (tag, "Onrebind method is called!");
Super.onrebind (INTENT);
}
}
private Button btnbind;
private Button btncancel;
private Button btnstatus;
//Keep the status of the started Service IBinder object, at the same time define a serviceConnection object
TestService2.myBinder Binder;
PriveConnection Conn = New Services Remarks this method during disconnection with service
@ Override
Public Void OSERVICEDISCONNECTED (ComponentName name) {
System.out.println ("----------------------");
//This method is called back when the connection between Activity and Service is successful
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("------Service Connected-- -----");
binder = (TestService2.MyBinder) service;
# super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnbind = (Button) findViewById(R.id.btnbind);
btncancel = (Button) find ViewById(R.id .btncancel);
btnstatus = (Button) findViewById(R.id.btnstatus);
final Intent intent = new Intent();
intent.setAction("com.jay.example.service.TEST_SERVICE2");
btnbind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//绑定service
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
btncancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//解除service绑定
unbindService(conn);
}
});
btnstatus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Service的count的值为:"
+binder.getCount(), Toast.LENGTH_SHORT).show();