Activity与Service通信

Android之Activity与Service通信

一、当Acitivity和Service处于同一个Application和进程时,通过继承Binder类来实现。

二..使用Messenger

三.通过broadcast(广播)的形式.当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar, 

四.使用AIDL的方法.点击我看AIDL的详情


  当一个Activity绑定到一个Service上时,它负责维护Service实例的引用,允许你对正在运行的Service进行一些方法调用。比如你后台有一个播放背景音乐的Service,这时就可以用这种方式来进行通信。

代码如下:

复制代码
/*************************Service代码****************************************/
public class LocalService extends Service {  
    private final IBinder binder = new LocalBinder();  

    public class LocalBinder extends Binder {  
        LocalService getService() {  
            return LocalService.this;  
        }  
    }  
  
    public IBinder onBind(Intent intent) {  
        return binder;  
    }  
}  

/*****************************Activity代码*************************************/
public class BindingActivity extends Activity {  
    LocalService localService;  

    private ServiceConnection mConnection = new ServiceConnection() {  
        public void onServiceConnected(ComponentName className,IBinder localBinder) {  
            localService = (LocalBinder) localBinder.getService();  
        }  
        public void onServiceDisconnected(ComponentName arg0) {  
            localService = null;  
        }  
    }; 

    protected void onStart() {  
        super.onStart();  

        Intent intent = new Intent(this, LocalService.class);  
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);  
    }  
  
    protected void onStop() {  
        super.onStop();  
        unbindService(mConnection);  
    }   

    public void printRandomNumber{  
          int num = localService.getRandomNumber();  
       System.out.println(num);
    }
}  
复制代码

代码解释:

使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running
onUnbind() -> onDestroy() ->Service stop

Activity能进行绑定得益于Service的接口onBind()。ServiceActivity的连接可以用ServiceConnection来实现,需要实现一个新的ServiceConnection,重写onServiceConnectedonServiceDisconnected方法。执行绑定,调用bindService方法,传入一个选择了要绑定的ServiceIntent(显式或隐式)和一个你实现了的ServiceConnection实例。一旦连接建立,你就能通Service的接口onBind()得到serviceBinder实例进而得到Service的实例引用。一旦Service对象找到,就能得到它的公共方法和属性。但这种方式,一定要在同一个进程和同一个Application里。


使用Messenger

   上面的方法只能在同一个进程里才能用,如果要与另外一个进程的Service进行通信,则可以用Messenger。

    其实实现IPC的方式,还有AIDL,但推荐使用Messenger,有两点好处:

      1. 使用Messenger方式比使用AIDL的方式,实现起来要简单很多

      2. 使用Messenger时,所有从Activity传过来的消息都会排在一个队列里,不会同时请求Service,所以是线程安全的。如果你的程序就是要多线程去访问Service,就可以用AIDL,不然最好使用Messenger的方式。

  不过,其实Messenger底层用的就是AIDL实现的,看一下实现方式,先看Service的代码:

 

  1. public class MessengerService extends Service {  
  2.     /** 用于Handler里的消息类型 */  
  3.     static final int MSG_SAY_HELLO = 1;  
  4.   
  5.     /** 
  6.      * 在Service处理Activity传过来消息的Handler 
  7.      */  
  8.     class IncomingHandler extends Handler {  
  9.         @Override  
  10.         public void handleMessage(Message msg) {  
  11.             switch (msg.what) {  
  12.                 case MSG_SAY_HELLO:  
  13.                     Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();  
  14.                     break;  
  15.                 default:  
  16.                     super.handleMessage(msg);  
  17.             }  
  18.         }  
  19.     }  
  20.   
  21.     /** 
  22.      * 这个Messenger可以关联到Service里的Handler,Activity用这个对象发送Message给Service,Service通过Handler进行处理。 
  23.      */  
  24.     final Messenger mMessenger = new Messenger(new IncomingHandler());  
  25.   
  26.     /** 
  27.      * 当Activity绑定Service的时候,通过这个方法返回一个IBinder,Activity用这个IBinder创建出的Messenger,就可以与Service的Handler进行通信了 
  28.      */  
  29.     @Override  
  30.     public IBinder onBind(Intent intent) {  
  31.         Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();  
  32.         return mMessenger.getBinder();  
  33.     }  
  34. }  

 

 再看一下Activity的代码:

  1. public class ActivityMessenger extends Activity {  
  2.     /** 向Service发送Message的Messenger对象 */  
  3.     Messenger mService = null;  
  4.   
  5.     /** 判断有没有绑定Service */  
  6.     boolean mBound;  
  7.   
  8.     private ServiceConnection mConnection = new ServiceConnection() {  
  9.         public void onServiceConnected(ComponentName className, IBinder service) {  
  10.             // Activity已经绑定了Service  
  11.             // 通过参数service来创建Messenger对象,这个对象可以向Service发送Message,与Service进行通信  
  12.             mService = new Messenger(service);  
  13.             mBound = true;  
  14.         }  
  15.   
  16.         public void onServiceDisconnected(ComponentName className) {  
  17.             mService = null;  
  18.             mBound = false;  
  19.         }  
  20.     };  
  21.   
  22.     public void sayHello(View v) {  
  23.         if (!mBound) return;  
  24.         // 向Service发送一个Message  
  25.         Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 00);  
  26.         try {  
  27.             mService.send(msg);  
  28.         } catch (RemoteException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32.   
  33.     @Override  
  34.     protected void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.main);  
  37.     }  
  38.   
  39.     @Override  
  40.     protected void onStart() {  
  41.         super.onStart();  
  42.         // 绑定Service  
  43.         bindService(new Intent(this, MessengerService.class), mConnection,  
  44.             Context.BIND_AUTO_CREATE);  
  45.     }  
  46.   
  47.     @Override  
  48.     protected void onStop() {  
  49.         super.onStop();  
  50.         // 解绑  
  51.         if (mBound) {  
  52.             unbindService(mConnection);  
  53.             mBound = false;  
  54.         }  
  55.     }  
  56. }  

 注意:以上写的代码只能实现从Activity向Service发送消息,如果想从Service向Activity发送消息,只要把代码反过来写就可以了。

 

3..使用AIDL

  如果知道上面两种方法,这个方法基本很少会用到。

详情请看这篇文章.http://blog.csdn.net/sanjay_f/article/details/38493257



4...broadcast(广播)的形式

当我们的进度发生变化的时候我们发送一条广播,然后在Activity的注册广播接收器,接收到广播之后更新ProgressBar,代码如下

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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>  

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }</span>  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值