Android Service與Activity之間通信的幾種方式

轉載至:http://blog.csdn.net/dawanganban/article/details/9763319



在Android中,Activity主要負責前臺頁面的展示,Service主要負責需要長期運行的任務,所以在我們實際開發中,就會常常遇到Activity與Service之間的通信,我們一般在Activity中啓動後臺Service,通過Intent來啓動,Intent中我們可以傳遞數據給Service,而當我們Service執行某些操作之後想要更新UI線程,我們應該怎麼做呢?接下來我就介紹兩種方式來實現Service與Activity之間的通信問題

  • 通過Binder對象

當Activity通過調用bindService(Intent service, ServiceConnection conn,int flags),我們可以得到一個Service的一個對象實例,然後我們就可以訪問Service中的方法,我們還是通過一個例子來理解一下吧,一個模擬下載的小例子,帶大家理解一下通過Binder通信的方式

首先我們新建一個工程Communication,然後新建一個Service類

  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7.   
  8. public class MsgService extends Service {  
  9.     /** 
  10.      * 進度條的最大值 
  11.      */  
  12.     public static final int MAX_PROGRESS = 100;  
  13.     /** 
  14.      * 進度條的進度值 
  15.      */  
  16.     private int progress = 0;  
  17.   
  18.     /** 
  19.      * 增加get()方法,供Activity調用 
  20.      * @return 下載進度 
  21.      */  
  22.     public int getProgress() {  
  23.         return progress;  
  24.     }  
  25.   
  26.     /** 
  27.      * 模擬下載任務,每秒鐘更新一次 
  28.      */  
  29.     public void startDownLoad(){  
  30.         new Thread(new Runnable() {  
  31.               
  32.             @Override  
  33.             public void run() {  
  34.                 while(progress < MAX_PROGRESS){  
  35.                     progress += 5;  
  36.                     try {  
  37.                         Thread.sleep(1000);  
  38.                     } catch (InterruptedException e) {  
  39.                         e.printStackTrace();  
  40.                     }  
  41.                       
  42.                 }  
  43.             }  
  44.         }).start();  
  45.     }  
  46.   
  47.   
  48.     /** 
  49.      * 返回一個Binder對象 
  50.      */  
  51.     @Override  
  52.     public IBinder onBind(Intent intent) {  
  53.         return new MsgBinder();  
  54.     }  
  55.       
  56.     public class MsgBinder extends Binder{  
  57.         /** 
  58.          * 獲取當前Service的實例 
  59.          * @return 
  60.          */  
  61.         public MsgService getService(){  
  62.             return MsgService.this;  
  63.         }  
  64.     }  
  65.   
  66. }</span>  
上面的代碼比較簡單,註釋也比較詳細,最基本的Service的應用了,相信你看得懂的,我們調用startDownLoad()方法來模擬下載任務,然後每秒更新一次進度,但這是在後臺進行中,我們是看不到的,所以有時候我們需要他能在前臺顯示下載的進度問題,所以我們接下來就用到Activity了

  1. Intent intent = new Intent("com.example.communication.MSG_ACTION");    
  2. bindService(intent, conn, Context.BIND_AUTO_CREATE);  

通過上面的代碼我們就在Activity綁定了一個Service,上面需要一個ServiceConnection對象,它是一個接口,我們這裏使用了匿名內部類

  1. <span style="font-family:System;">  ServiceConnection conn = new ServiceConnection() {  
  2.           
  3.         @Override  
  4.         public void onServiceDisconnected(ComponentName name) {  
  5.               
  6.         }  
  7.           
  8.         @Override  
  9.         public void onServiceConnected(ComponentName name, IBinder service) {  
  10.             //返回一個MsgService對象  
  11.             msgService = ((MsgService.MsgBinder)service).getService();  
  12.               
  13.         }  
  14.     };</span>  

在onServiceConnected(ComponentName name, IBinder service) 回調方法中,返回了一個MsgService中的Binder對象,我們可以通過getService()方法來得到一個MsgService對象,然後可以調用MsgService中的一些方法,Activity的代碼如下

  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.ProgressBar;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     private MsgService msgService;  
  17.     private int progress = 0;  
  18.     private ProgressBar mProgressBar;  
  19.       
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.           
  26.           
  27.         //綁定Service  
  28.         Intent intent = new Intent("com.example.communication.MSG_ACTION");  
  29.         bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  30.           
  31.           
  32.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  33.         Button mButton = (Button) findViewById(R.id.button1);  
  34.         mButton.setOnClickListener(new OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(View v) {  
  38.                 //開始下載  
  39.                 msgService.startDownLoad();  
  40.                 //監聽進度  
  41.                 listenProgress();  
  42.             }  
  43.         });  
  44.           
  45.     }  
  46.       
  47.   
  48.     /** 
  49.      * 監聽進度,每秒鐘獲取調用MsgService的getProgress()方法來獲取進度,更新UI 
  50.      */  
  51.     public void listenProgress(){  
  52.         new Thread(new Runnable() {  
  53.               
  54.             @Override  
  55.             public void run() {  
  56.                 while(progress < MsgService.MAX_PROGRESS){  
  57.                     progress = msgService.getProgress();  
  58.                     mProgressBar.setProgress(progress);  
  59.                     try {  
  60.                         Thread.sleep(1000);  
  61.                     } catch (InterruptedException e) {  
  62.                         e.printStackTrace();  
  63.                     }  
  64.                 }  
  65.                   
  66.             }  
  67.         }).start();  
  68.     }  
  69.       
  70.     ServiceConnection conn = new ServiceConnection() {  
  71.         @Override  
  72.         public void onServiceDisconnected(ComponentName name) {  
  73.               
  74.         }  
  75.           
  76.         @Override  
  77.         public void onServiceConnected(ComponentName name, IBinder service) {  
  78.             //返回一個MsgService對象  
  79.             msgService = ((MsgService.MsgBinder)service).getService();  
  80.               
  81.         }  
  82.     };  
  83.   
  84.     @Override  
  85.     protected void onDestroy() {  
  86.         unbindService(conn);  
  87.         super.onDestroy();  
  88.     }  
  89.   
  90.   
  91. }</span><span style="font-family: simsun;">  
  92. </span>  
其實上面的代碼我還是有點疑問,就是監聽進度變化的那個方法我是直接在線程中更新UI的,不是說不能在其他線程更新UI操作嗎,可能是ProgressBar比較特殊吧,我也沒去研究它的源碼,知道的朋友可以告訴我一聲,謝謝!

上面的代碼就完成了在Service更新UI的操作,可是你發現了沒有,我們每次都要主動調用getProgress()來獲取進度值,然後隔一秒在調用一次getProgress()方法,你會不會覺得很被動呢?可不可以有一種方法當Service中進度發生變化主動通知Activity,答案是肯定的,我們可以利用回調接口實現Service的主動通知,不理解回調方法的可以看看http://blog.csdn.net/xiaanming/article/details/8703708

新建一個回調接口

  1. public interface OnProgressListener {  
  2.     void onProgress(int progress);  
  3. }  
MsgService的代碼有一些小小的改變,爲了方便大家看懂,我還是將所有代碼貼出來

  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7.   
  8. public class MsgService extends Service {  
  9.     /** 
  10.      * 進度條的最大值 
  11.      */  
  12.     public static final int MAX_PROGRESS = 100;  
  13.     /** 
  14.      * 進度條的進度值 
  15.      */  
  16.     private int progress = 0;  
  17.       
  18.     /** 
  19.      * 更新進度的回調接口 
  20.      */  
  21.     private OnProgressListener onProgressListener;  
  22.       
  23.       
  24.     /** 
  25.      * 註冊回調接口的方法,供外部調用 
  26.      * @param onProgressListener 
  27.      */  
  28.     public void setOnProgressListener(OnProgressListener onProgressListener) {  
  29.         this.onProgressListener = onProgressListener;  
  30.     }  
  31.   
  32.     /** 
  33.      * 增加get()方法,供Activity調用 
  34.      * @return 下載進度 
  35.      */  
  36.     public int getProgress() {  
  37.         return progress;  
  38.     }  
  39.   
  40.     /** 
  41.      * 模擬下載任務,每秒鐘更新一次 
  42.      */  
  43.     public void startDownLoad(){  
  44.         new Thread(new Runnable() {  
  45.               
  46.             @Override  
  47.             public void run() {  
  48.                 while(progress < MAX_PROGRESS){  
  49.                     progress += 5;  
  50.                       
  51.                     //進度發生變化通知調用方  
  52.                     if(onProgressListener != null){  
  53.                         onProgressListener.onProgress(progress);  
  54.                     }  
  55.                       
  56.                     try {  
  57.                         Thread.sleep(1000);  
  58.                     } catch (InterruptedException e) {  
  59.                         e.printStackTrace();  
  60.                     }  
  61.                       
  62.                 }  
  63.             }  
  64.         }).start();  
  65.     }  
  66.   
  67.   
  68.     /** 
  69.      * 返回一個Binder對象 
  70.      */  
  71.     @Override  
  72.     public IBinder onBind(Intent intent) {  
  73.         return new MsgBinder();  
  74.     }  
  75.       
  76.     public class MsgBinder extends Binder{  
  77.         /** 
  78.          * 獲取當前Service的實例 
  79.          * @return 
  80.          */  
  81.         public MsgService getService(){  
  82.             return MsgService.this;  
  83.         }  
  84.     }  
  85.   
  86. }</span>  
Activity中的代碼如下

  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.ProgressBar;  
  14.   
  15. public class MainActivity extends Activity {  
  16.     private MsgService msgService;  
  17.     private ProgressBar mProgressBar;  
  18.       
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.           
  25.           
  26.         //綁定Service  
  27.         Intent intent = new Intent("com.example.communication.MSG_ACTION");  
  28.         bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  29.           
  30.           
  31.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  32.         Button mButton = (Button) findViewById(R.id.button1);  
  33.         mButton.setOnClickListener(new OnClickListener() {  
  34.               
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 //開始下載  
  38.                 msgService.startDownLoad();  
  39.             }  
  40.         });  
  41.           
  42.     }  
  43.       
  44.   
  45.     ServiceConnection conn = new ServiceConnection() {  
  46.         @Override  
  47.         public void onServiceDisconnected(ComponentName name) {  
  48.               
  49.         }  
  50.           
  51.         @Override  
  52.         public void onServiceConnected(ComponentName name, IBinder service) {  
  53.             //返回一個MsgService對象  
  54.             msgService = ((MsgService.MsgBinder)service).getService();  
  55.               
  56.             //註冊回調接口來接收下載進度的變化  
  57.             msgService.setOnProgressListener(new OnProgressListener() {  
  58.                   
  59.                 @Override  
  60.                 public void onProgress(int progress) {  
  61.                     mProgressBar.setProgress(progress);  
  62.                       
  63.                 }  
  64.             });  
  65.               
  66.         }  
  67.     };  
  68.   
  69.     @Override  
  70.     protected void onDestroy() {  
  71.         unbindService(conn);  
  72.         super.onDestroy();  
  73.     }  
  74.   
  75.   
  76. }  
  77. </span>  
用回調接口是不是更加的方便呢,當進度發生變化的時候Service主動通知Activity,Activity就可以更新UI操作了

當我們的進度發生變化的時候我們發送一條廣播,然後在Activity的註冊廣播接收器,接收到廣播之後更新ProgressBar,代碼如下

  1. package com.example.communication;  
  2. <span style="font-family:System;">  
  3. import android.app.Activity;  
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12. import android.widget.ProgressBar;  
  13.   
  14. public class MainActivity extends Activity {  
  15.     private ProgressBar mProgressBar;  
  16.     private Intent mIntent;  
  17.     private MsgReceiver msgReceiver;  
  18.       
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.           
  25.         //動態註冊廣播接收器  
  26.         msgReceiver = new MsgReceiver();  
  27.         IntentFilter intentFilter = new IntentFilter();  
  28.         intentFilter.addAction("com.example.communication.RECEIVER");  
  29.         registerReceiver(msgReceiver, intentFilter);  
  30.           
  31.           
  32.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  33.         Button mButton = (Button) findViewById(R.id.button1);  
  34.         mButton.setOnClickListener(new OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(View v) {  
  38.                 //啓動服務  
  39.                 mIntent = new Intent("com.example.communication.MSG_ACTION");  
  40.                 startService(mIntent);  
  41.             }  
  42.         });  
  43.           
  44.     }  
  45.   
  46.       
  47.     @Override  
  48.     protected void onDestroy() {  
  49.         //停止服務  
  50.         stopService(mIntent);  
  51.         //註銷廣播  
  52.         unregisterReceiver(msgReceiver);  
  53.         super.onDestroy();  
  54.     }  
  55.   
  56.   
  57.     /** 
  58.      * 廣播接收器 
  59.      * @author len 
  60.      * 
  61.      */  
  62.     public class MsgReceiver extends BroadcastReceiver{  
  63.   
  64.         @Override  
  65.         public void onReceive(Context context, Intent intent) {  
  66.             //拿到進度,更新UI  
  67.             int progress = intent.getIntExtra("progress"0);  
  68.             mProgressBar.setProgress(progress);  
  69.         }  
  70.           
  71.     }  
  72.   
  73. }  
  74. </span>  

  1. <span style="font-family:System;">package com.example.communication;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6.   
  7. public class MsgService extends Service {  
  8.     /** 
  9.      * 進度條的最大值 
  10.      */  
  11.     public static final int MAX_PROGRESS = 100;  
  12.     /** 
  13.      * 進度條的進度值 
  14.      */  
  15.     private int progress = 0;  
  16.       
  17.     private Intent intent = new Intent("com.example.communication.RECEIVER");  
  18.       
  19.   
  20.     /** 
  21.      * 模擬下載任務,每秒鐘更新一次 
  22.      */  
  23.     public void startDownLoad(){  
  24.         new Thread(new Runnable() {  
  25.               
  26.             @Override  
  27.             public void run() {  
  28.                 while(progress < MAX_PROGRESS){  
  29.                     progress += 5;  
  30.                       
  31.                     //發送Action爲com.example.communication.RECEIVER的廣播  
  32.                     intent.putExtra("progress", progress);  
  33.                     sendBroadcast(intent);  
  34.                       
  35.                     try {  
  36.                         Thread.sleep(1000);  
  37.                     } catch (InterruptedException e) {  
  38.                         e.printStackTrace();  
  39.                     }  
  40.                       
  41.                 }  
  42.             }  
  43.         }).start();  
  44.     }  
  45.   
  46.       
  47.   
  48.     @Override  
  49.     public int onStartCommand(Intent intent, int flags, int startId) {  
  50.         startDownLoad();  
  51.         return super.onStartCommand(intent, flags, startId);  
  52.     }  
  53.   
  54.   
  55.   
  56.     @Override  
  57.     public IBinder onBind(Intent intent) {  
  58.         return null;  
  59.     }  
  60.   
  61.   
  62. 總結:

    1. Activity調用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service對象的一個引用,這樣Activity可以直接調用到Service中的方法,如果要主動通知Activity,我們可以利用回調方法
    2.  Service向Activity發送消息,可以使用廣播,當然Activity要註冊相應的接收器。比如Service要向多個Activity發送同樣的消息的話,用這種方法就更好

發佈了11 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章