Android review basic Service usage
In the past two days, I will review my knowledge about the Android Service and summarize it before the memory fades away. This document describes the basic concepts and usage of services, cross-process Service calling, and common system services. Therefore, this article is very difficult. It is only applicable to students who want to review Service knowledge points or who do not know much about the Service. For services such as the source code, I will share it with my husband after analysis and research.
I. Service Basics
I believe that anyone who has been familiar with Android development knows about Service more or less. What is Service? Service is the most similar component to Activity among the four Android components. It has its own life cycle completely, but it does not have the same gorgeous appearance as Activity. It pays silently in the background all the year round. The Service is also an executable program. As mentioned above, it has its own lifecycle, and its creation and configuration process are extremely similar to those of the Activity. In addition, Activity and Service have a common parent Context, so they can call methods defined in Context, such as getResources () and getContentResolver.
1. simple use of services:
Two steps are required for Service Development: (1) define a subclass that inherits the Service. (2) configure the Service in the AndroidManifest. xml file.
Before developing the first Service, let's take a look at the series of Service lifecycle methods:
(1) IBinder onBind (Intent intent): This method is required by the Service subclass. This method returns an IBinder object through which the application can communicate with the Service component.
(2) void onCreate (): This method is called back immediately after the Service is created for the first time.
(3) void onDestroy (): This method is called back before the Service is closed.
(4) void onStartCommand (Intent intent, int flags, int startId): the early version of this method is void onStart (Intent intent, int startId). Each time the client calls startService (Intent) the method is called back when the Service is started.
(5) boolean onUnbind (Intent intent): This method is called back when all clients bound to this Service are disconnected.
The code for developing our first Service is as follows:
Package com. gc. servicetest; import android. app. notification; import android. app. pendingIntent; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; import android. util. log;/*** Note: The onCreate () method is called only when the Service is created for the first time. If the current Service has been created, * call the startService method regardless of the method, the onCreate () method will not be executed any more. * @ Author Android General **/public class MyService extends Service {public static final String TAG = MyService. class. getSimpleName (); // required method @ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubLog. v (TAG, onBind () executed); return null;} // call back this method when the Service is created @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); Log. v (TAG, onCreate () executed); Log. v (TAG, MyService thread id is + Thread. currentThread (). getId ();} // call back this method when the Service is started @ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog. v (TAG, onStartCommand () executed); return super. onStartCommand (intent, flags, startId);} // call back this method before the Service is disabled @ Overridepublic void onDestroy () {// TODO Auto-generated method stubsuper. onDestroy (); Log. v (TAG, onDestroy () executed );}}
The above Service does nothing-it only overrides the onCreate (), onStartCommand (), onDestroy (), onBind () and other methods of the Service component. If you want the Service component to do something, you only need to define the relevant business code in the onCreate () or onStartCommand () method. Now we have completed the first step of Service development. Let's take the second step together. The second step is very simple. The configuration of Service in AndroidManifest. xml is the same as the configuration of Activity in this file, but the tag is , One is. The following code configures MyService:
After the two steps are completed, we have developed a Service component, and then we can run the Service in the program. There are two ways to run the Service in the Android system:
(1) startService () method of Context: This method is used to start the Service. There is no association between the visitor and the Service. Even if the visitor exits, the Service continues to run.
(2) bindService () method of Context: This method is used to enable the Service. When a visitor is bound to the Service, the Service is terminated once the visitor exits.
Next, let's take a look at how to use these two methods to start the Myservice we just developed. We use Activity as a Service Visitor. The Activity Interface contains four buttons, because the code is simple, the layout file is no longer provided here. The MainActivity code is as follows:
Package com. gc. servicetest; import com. gc. servicetest. myService. myBinder; import android. app. activity; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; import android. OS. bundle; import android. OS. IBinder; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. view. onClickListener; import android. widget. button;/***** @ author Android General **/public class MainActivity extends Activity implements OnClickListener {public static final String TAG = MainActivity. class. getSimpleName (); private Button mBtnStartService; private Button mBtnStopService; private Button mBtnBindService; private Button mBtnUnBindService; private MyService. myBinder myBinder; private ServiceConnection connection = new ServiceConnection () {@ Overridepublic void onServiceDisconnected (ComponentName name) {// TODO Auto-generated method stubLog. v (TAG, onServiceDisconnected () executed); Log. v (TAG, onServiceDisconnected () executed name + name) ;}@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {// TODO Auto-generated method stubLog. v (TAG, onServiceConnected () executed); Log. v (TAG, onServiceConnected () executed name + name); myBinder = (MyBinder) service; myBinder. startDownload () ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initUI (); setListener (); Log. v (TAG, MainActivity thread id is + Thread. currentThread (). getId ();} public void initUI () {mBtnStartService = (Button) findViewById (R. id. start_service); mBtnStopService = (Button) findViewById (R. id. stop_service); mBtnBindService = (Button) findViewById (R. id. bind_service); mBtnUnBindService = (Button) findViewById (R. id. unbind_service);} public void setListener () {mBtnStartService. setOnClickListener (this); mBtnStopService. setOnClickListener (this); mBtnBindService. setOnClickListener (this); mBtnUnBindService. setOnClickListener (this) ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. start_service: Intent mStartIntent = new Intent (this, MyService. class); startService (mStartIntent); break; case R. id. stop_service: Intent mStopIntent = new Intent (this, MyService. class); stopService (mStopIntent); break; case R. id. bind_service: Intent mBindIntent = new Intent (this, MyService. class); bindService (mBindIntent, connection, BIND_AUTO_CREATE); break; case R. id. unbind_service: unbindService (connection); break; default: break ;}}}So far, we have written a program with the Service function. Then we run the program, click Start Service, and then click Stop Service. The following print result is displayed:
If you click the Start Sevice button three times in a row without shutting down the Service, the program starts the Service three times in a row. The print information is as follows:
From the two different operations and print information above, we have verified the correctness of the content mentioned in the MyService comment section, as follows:
The onCreate () method is called only when the Service is created for the first time. If the current Service has been created, the onCreate () method will not be executed no matter how the startService method is called.
Now we know the first method, so let's take a look at the second method:
In the first method, there are basically no many associations between MyService and MainActivity, so MyService and MainActivity cannot communicate or exchange data. If you want to call methods or exchange data between MyService and MainActivity, use the second method to start MyService, that is, use bindService () and unbindService () to start and close the Service. Before using the second method to start MyService, you must modify the code of MyService. The modified code is as follows:
public class MyService extends Service{public static final String TAG=MyService.class.getSimpleName();private MyBinder mBinder=new MyBinder();@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.v(TAG, onBind() executed);return mBinder;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.v(TAG, onCreate() executed);Log.v(TAG, MyService thread id is +Thread.currentThread().getId()); }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.v(TAG, onStartCommand() executed);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Log.v(TAG, onDestroy() executed);}class MyBinder extends Binder{public void startDownload(){Log.v(TAG, startDownload() executed);}}}Before proceeding, let's take a look at the bindService method:
The source code of the bindService () method of Context is as follows:
public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); }Here we will explain the three parameters of this method:
Service: Specifies the Service to be started through Intent.
Conn: this parameter is a ServiceConnection object used to listen to the connection between the visitor and the Service. When the connection between the visitor and the Service is successful, the onServiceConnected (ComponentName, IBinder service) method of the ServiceConnecttion object will be called back. When the host process of the Service is terminated due to exceptions or other reasons, the onServiceDisconnected (ComponentName) method of the ServiceConnection object is called back when the Service is disconnected from the visitor.
Note: When the caller actively disconnects from the Service through the unBindService () method, the onServiceDisconnected (ComponentName) method of the ServiceConnection object will not be called.
Flags: Specifies whether to automatically create a Service when binding (if the Service has not been created ). This parameter can be specified as 0 (not automatically created) or BIND_AUTO_CREATE (automatically created ).
Note that the onServiceConnected method of the ServiceConnection object contains an IBinder object, which can implement communication with the bound Service.
Well, it's a bit dizzy if it's so much. Let's take a look at the execution effect of the second method to start MyService. Run the program, click Bind Service, and then click unBind Service. The print information is as follows:
We can see that MainActivity has successfully communicated with MyService. The startDownload () method is called in the onServiceConnected method of the connection Member object of MainActivity.
The following is a summary:
Two steps are required for Service Development: (1) define a subclass that inherits the Service. (2) configure the Service in the AndroidManifest. xml file.
There are two ways to start a Service: (1) startService method (2) bindService Method
When you start a Service in startService mode, there is basically no association between the Service and the visitor. You can start a Service in bindService mode to implement communication between the Service and its visitors. So how does one communicate when the Service is started through bindService? According to this case, when we develop the MyService class, we must implement IBinder onBinder (Intent intent). When we start MyService through the bindService method, we have bound MainActivity and MyService. At this time, the IBinder object returned by the onBind method of MyService will be passed to the onServiceConnected (ComponentName, IBinder service) in the connection of the MainActivity member) in this way, MainActivity can communicate with MyService through the IBinder object.
Careful communication will find that the onStartCommand method is called when the Service is started through startService, but the onStartCommand method is not called when the Service is started using the bindService method. Why? This is because the Service is started in two ways, resulting in slightly different Service lifecycles. In the next Service lifecycle, I will explain it clearly.
Well, I think the basic knowledge of the Service should be almost the same as BB. I will provide this Demo at the end of the article. If it is helpful to you, I can try it out, if you have any questions or I have not explained them clearly, please leave a message. Thank you.