Communication between Service and Activity

Source: Internet
Author: User

Communication between Service and Activity

There are two ways to start the Service, one is through the start method, the other is through the bind method, after starting the Service through the start method, the components and services that start the service have little contact with each other. Therefore, to be able to communicate with the Service, you can only use the bind method. The following describes several steps: (the Service in the demo provides a download function, and then decides when to start the download in the Activity, and check the download progress at any time)

Step 1:

Create an internal class in the Service class inherited from the Binder (the onBind method returns the IBinder interface, and the Binder class is the implementation class of the IBinder Interface) (we can see that an interface is also implemented here, the methods in the interface are implemented, and an additional method is provided. This additional method does not require Activity access, so we use the interface method here ):

// 1. private class DownloadBinder extends Binder implements DownloadBinderImpl {@ Overridepublic void startDownload () {Log. I (TAG, "startDownload") ;}@ Overridepublic int getProgress () {Log. I (TAG, "getProgress"); return 0;} public void Inner () {Log. I (TAG, "I don't want Activity to use me ");}}
Step 2: The interface mentioned above:

package com.dystu.servicedemo;public interface DownloadBinderImpl {public void startDownload();public int getProgress();}

Step 3: return the DownloadBinder instance in the onBind () method of the Service:

@Overridepublic IBinder onBind(Intent intent) {Log.i(TAG, "onBind");return new DownloadBinder();}

Step 4: bind the service in the Activity:

public void bind(View view) {Intent intent = new Intent(this, MyService.class);bindService(intent, conn, BIND_AUTO_CREATE);}
Step 5: Create an anonymous internal ServiceConnection class and implement the onServiceConnected and onServiceDisconnected methods. These two methods will be called when the service is successfully bound and unbound.

Private class MyConn implements ServiceConnection {@ Overridepublic void onServiceConnected (ComponentName name, IBinder service) {dbi = (DownloadBinderImpl) service; Log. I (TAG, "successfully Bound Service ---- onServiceConnected executed") ;}@ Overridepublic void onServiceDisconnected (ComponentName name) {Log. I (TAG, "Unbind service ---- onServiceDisconnected executed ");}}

Step 6:

How to call a service:

Public void call (View view) {if (dbi! = Null) {dbi. startDownload (); dbi. getProgress ();} else {Toast. makeText (this, "bind service first", 0 ). show ();}}

It can also be executed in onServiceConnected.

Implementation results:


Click bind: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20150109/2015010908594548.png" alt = "\">


Click call:



Click unbind:




Complete code:

Interface:

package com.dystu.servicedemo;public interface DownloadBinderImpl {public void startDownload();public int getProgress();}

Service:

Package com. dystu. servicedemo; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; import android. util. log; public class MyService extends Service {private static final String TAG = "MyService"; // 2. @ Overridepublic IBinder onBind (Intent intent) {Log. I (TAG, "onBind"); return new DownloadBinder () ;}@ Overridepublic boolean onUnbind (Intent intent) {Log. I (TAG, "onUnbind"); return super. onUnbind (intent) ;}@ Overridepublic void onCreate () {super. onCreate (); Log. I (TAG, "onCreate") ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {Log. I (TAG, "onStartCommand"); return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic void onDestroy () {super. onDestroy (); Log. I (TAG, "onDestroy");} // 1. private class DownloadBinder extends Binder implements DownloadBinderImpl {@ Overridepublic void startDownload () {Log. I (TAG, "startDownload") ;}@ Overridepublic int getProgress () {Log. I (TAG, "getProgress"); return 0;} public void Inner () {Log. I (TAG, "I don't want Activity to use me ");}}}

Main Interface layout:

     
           
       
  
 


MainActivity:

Package com. dystu. servicedemo; 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. view; import android. widget. toast; public class MainActivity extends Activity {public static final String TAG = "MainActivity"; private MyConn Conn; DownloadBinderImpl dbi; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); conn = new MyConn ();} // 3. public void bind (View view) {Intent intent = new Intent (this, MyService. class); bindService (intent, conn, BIND_AUTO_CREATE);} public void unbind (View view) {unbindService (conn); dbi = null;} public void call (View vi Ew) {if (dbi! = Null) {dbi. startDownload (); dbi. getProgress ();} else {Toast. makeText (this, "bind service first", 0 ). show () ;}// 4. private class MyConn implements ServiceConnection {@ Overridepublic void onServiceConnected (ComponentName name, IBinder service) {dbi = (DownloadBinderImpl) service; Log. I (TAG, "successfully Bound Service ---- onServiceConnected executed") ;}@ Overridepublic void onServiceDisconnected (ComponentName name) {Log. I (TAG, "Unbind service ---- onServiceDisconnected executed ");}}}


PS:

Normally, the onServiceDisconnected () method in ServiceConnection is not called, and its call time is when the Service is destroyed by an exception, for example, this method is automatically called only when memory resources are insufficient.



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.