Service of four Android Components

Source: Internet
Author: User

Service of four Android Components

Among the four Android components, Service and Activity are similar. The difference is that Activity is used for the foreground, and Service is used for the background.

When your program does not need to use components to render the interface, it uses Service. A typical example is to play music. You still need to play music after exiting the interface. In this case, you need to run the Service background.

 

Service creation 1. Define a subclass that inherits the Service 2. Configure the Service in the AndroidMainifest. xml file. Is this process similar to creating an Activity. Right.
Service start and stop 1. Call the startService () and stopService () methods defined in Context. However, the Service started in this way cannot communicate with the visitor or exchange data. 2. Enable and disable bindService (Intent service, ServiceConnection conn, int flags) and unbindService () to implement communication and data exchange.
What is the principle of communication and data exchange? First, let's take a look at the meaning of the three parameters bindService (Intent service, ServiceConnection conn, int flags):> service: Undoubtedly this is the service to be started> conn: This is a ServiceConnection object, the function is to determine the connection. When the connection is successful, the onServiceConnected () method of the ServiceConnection object will be called back. When the connection fails or an exception occurs, in this case, when the caller actively disconnects, The onServiceDisconnected () method of ServiceConnection will be called back;> flags: whether to automatically create a Service when binding (if not yet created ), it can be set to 0-not automatically created; BIND_AUTO_CREATE-automatically created;
The key to successful connection lies in the second parameter. The onServiceConnected method of this parameter object has an IBinder object, which is used to transmit data like a communication messenger. The following is an example of the Android crazy handout source code: onBind () in the Service subclass is a required method. This method returns an IBinder object and communicates with the caller. The returned IBinder object is usually used to inherit the Binder to implement its own IBinder object.
Public class BindService extends Service {private int count; private boolean quit; // defines the object private MyBinder binder = new MyBinder () returned by the onBinder method (); // implement the IBinder class public class MyBinder extends Binder by inheriting the Binder // ① {public int getCount () {// obtain the Service running status: countreturn count ;}} // required method. This method is called back when the Service is bound @ Overridepublic IBinder onBind (Intent intent) {System. out. println ("Service is Binded"); // return the IBinder object return Binder;} // call back this method when the Service is created. @ Overridepublic void onCreate () {super. onCreate (); System. out. println ("Service is Created"); // start a Thread and dynamically modify the count status value new Thread () {@ Overridepublic void run () {while (! Quit) {try {Thread. sleep (1000);} catch (InterruptedException e) {}count ++ ;}}}. start () ;}// call back this method when the Service is disconnected @ Overridepublic boolean onUnbind (Intent intent) {System. out. println ("Service is Unbinded"); return true;} // call back this method before the Service is disabled. @ Overridepublic void onDestroy () {super. onDestroy (); this. quit = true; System. out. println ("Service is Destroyed ");}}


The following is an Activity to bind the Service. In the Activity, define a MyBinder class in the Service to access the internal status of the Service.
Public class BindServiceTest extends Activity {Button bind, unbind, getServiceStatus; // maintain the BindService object of the started Service. myBinder binder; // defines a ServiceConnection object private ServiceConnection conn = new ServiceConnection () {// calls back this method when the Activity and Service are successfully connected @ Overridepublic void onServiceConnected (ComponentName name, IBinder service) {System. out. println ("-- Service Connected --"); // obtain the MyBinder object binder = (BindService. myBinder) service; //} // this method is called back when the Activity is disconnected from the Service. @ Overridepublic void onServiceDisconnected (ComponentName name) {System. out. println ("-- Service Disconnected --") ;};@ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // obtain the start, stop, and getServiceStatus buttons in the Program Interface bind = (Button) findViewById (R. id. bind); unbind = (Button) findViewById (R. id. unbind); getServiceStatus = (Button) findViewById (R. id. getServiceStatus); // create Intentfinal Intent intent = new Intent (); // set the Action attribute Intent for intent. setAction ("org. crazyit. service. BIND_SERVICE "); bind. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// bind specified SerivcebindService (intent, conn, Service. BIND_AUTO_CREATE) ;}}); unbind. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// unbind SerivceunbindService (conn) ;}}); getServiceStatus. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View source) {// obtain and display the count value of the Service Toast. makeText (BindServiceTest. this, "The count value of Serivce is:" + binder. getCount (), Toast. LENGTH_SHORT ). show (); // ② }});}}

Two different methods of starting a Service have different lifecycles.
Non-binding Service lifecycle: onCreate ()-> onStartCommand ()-> onDestroy () binding Service lifecycle: onCreate ()-> onBind ()-> onUnbind () -> onDestroy ()

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