Activity与Service通信的四种方式

来源:互联网 发布:淘宝怎么开点卡充值店 编辑:程序博客网 时间:2024/06/05 20:49

1、Binder

//activity中的代码片段private MyService.MyBinder myBinder = null;private ServiceConnection serviceConnection = newServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            myBinder = (MyService.MyBinder)service;        }        @Override        public void onServiceDisconnected(ComponentName name) {        }//通过Service中定义的Binder内部类修改Service中的数据,Activity中调用:       if(myBinder != null){           myBinder.setData("dataValue");       }//service中定义的内部类:public class MyBinder extends Binder {        public MyService getService(){            return MyService.this;        }        public void setData(String dataValue){            data = dataValue;        }        public String getData(){            return data;        }//service中的onBind方法中返回内部类的一个实例:  @Nullable    @Override    public IBinder onBind(Intent intent) {        return new MyBinder();    }

2、Intent

//activity中通过Intent传递数据到serviceIntent intent = new Intent(TestActivity.this, MyService.class);intent.putExtra("dataKey","dataValue");startService(intent);//在service中的onStartCommand方法中获取Intent中的数据@Override    public int onStartCommand(Intent intent, int flags, int startId) {       String dataVaule = intent.getStringExtra("dataKey");       return super.onStartCommand(intent, flags, startId);   }

3、接口Interface

在Service中定义一个接口和接口变量,在需要传递数据的地方调用接口方法进行数据传递,然后在Activity中实现该接口并重写接口方法,就能获取Service中传递过来的数据

Service中的代码:// 需要数据时if (serviceCallBack != null) {       // 调用接口方法,将需要传递的值作为参数传递       serviceCallBack.getServiceData(data);   } //定义的接口public interface ServiceCallBack {        void getServiceData(String data);}//activity代码:implements ServiceCallBack @Override    public void getServiceData(String data) {        // 这里的 data 参数便是从 Service 传递过来的数据    }

4、Broadcast广播接收

这种方式比较简单,在Service中利用Intent发送一个广播,在Activity中注册相应的广播接收,即可获取Intent中传递过来的数据。

1 0