[Android learning] Android Service (2) -- bind a local Service

Source: Internet
Author: User

In the previous blog, I briefly introduced the Service usage, that is, Service Startup and shutdown. However, when a program starts or closes a Service through startService () and stopService (), there are basically no many associations between the Service and its visitors, therefore, communication and data exchange between services and visitors are not allowed. As we usually send a mail, when the mail is sent, we cannot get whether the mail is delivered, the status in the mail sending process, and so on. When we want this information, that is, when we want to call methods and exchange data between services and visitors, we should use bindService () and unbindService () Methods to start and close services.

 

The complete bindService () method of Context is named bindService (Intent service, ServiceConnection conn, int flags)

Service: Specifies the Service to be started through Intent.

Conn: this parameter is a ServiceConnection object used to listen to the connection status 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 ServiceConnection object will be called back. When the host process of the Service is terminated due to an exception or other reasons, the onServiceDisconnected (ComponentName) method of the ServiceConnection object is called back when the Service is disconnected from the visitor.

Flags: Specifies whether to actively create a Service when binding (if the Service has not been created ). This parameter can be 0 (not automatically created) or BIND_AUTO_CREATE (automatically created ).

------ When the caller actively disconnects from the Service through the unBindService method, the onServiceDisconnected (ComponentName) method of the ServiceConnection object will not be called.

 

There is an Ibinder object in the onServiceConnected method of the ServiceConnection object. This object can communicate with the bound Service.

 

The following example demonstrates how to bind a local Service to an Activity and obtain the running status of the Service, that is, to communicate with the Service.

BinderService. java:

 

package com.ye_yun_lin.binderserviceactivity;import android.R.integer;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class BinderService extends Service{private int count;private boolean quit;private MyBinder myBinder=new MyBinder();public class MyBinder extends Binder{public int getcount(){return count;}}@Overridepublic IBinder onBind(Intent intent) {System.out.println("Service is binded");return myBinder;}@Overridepublic void onCreate() {super.onCreate();System.out.println("Service is created");new Thread(){@Overridepublic void run() {while (!quit) {try {Thread.sleep(1000);} catch (Exception e) {}count++;}}}.start();}@Overridepublic void onDestroy() {super.onDestroy();this.quit=true;System.out.println("Service is Destroyed");}@Overridepublic boolean onUnbind(Intent intent) {System.out.println("Service is unbinded");return super.onUnbind(intent);}}

Configure Service:

 

 

        
             
                              
          
 

MainActivity. java:

 

 

Package com. ye_yun_lin.binderserviceactivity; import android. OS. bundle; import android. OS. IBinder; import android. app. activity; import android. app. service; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {private Button bindButton, unbindButton, buttonStatusButton; BinderService. myBinder binder; private ServiceConnection conn = new ServiceConnection () {// call back this method when the Activity and Service are disconnected @ Overridepublic void onServiceDisconnected (ComponentName name) {System. out. println ("-- Service Didconnected --");} // call back this method when the Activity and Service are successfully connected @ Overridepublic void onServiceConnected (ComponentName, IBinder service) {System. out. println ("-- Service Connected --"); binder = (BinderService. myBinder) service ;};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bindButton = (Button) findViewById (R. id. bindservice); unbindButton = (Button) findViewById (R. id. unbindservice); buttonStatusButton = (Button) findViewById (R. id. servicestatus); final Intent intent = new Intent (); intent. setAction ("com. ye_yun_lin.binderserviceactivity.BinderService.local "); bindButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {bindService (intent, conn, Service. BIND_AUTO_CREATE) ;}}); unbindButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {unbindService (conn) ;}}); buttonStatusButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Toast. makeText (MainActivity. this, "The count value of Service is:" + binder. getcount (), Toast. LENGTH_SHORT ). show ();}});}}

Result:

 

Through the above two examples, we can get the Service lifecycle:

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.