Service是android四大组件之一,通常很多后台的工作会交给Service,如音乐的播放什么的,这里不介绍Service的生命周期什么的,主要介绍如何绑定Service并进行信息传递。
一、同个App绑定Service
步骤1:自定义一个继承Service的类,如叫MyService;
步骤2:在MyService类中自定义一个继承Binder的内部类,如叫MyIBinder;
步骤3:重写MyService的onBind(Intent intent)方法,返回一个MyIBinder的实例对象,参数intent为绑定MyService的Activity或ContentProvider传过来的(信息可通过intent传递过来);
步骤4:在MyIBinder类中实现一些方法,将要从Service传递出去的信息通过这些方法返回。
(以上是在Service部分做的操作,接下去的步骤是在需要绑定Service的方法做的操作)
步骤5:实例化一个ServiceConnection的对象,并重写onServiceConnected(ComponentName componentName, IBinder iBinder)和onServiceDisconnected(ComponentName componentName)方法;
onServiceConnected:在service绑定时执行,参数componentName是组件的名称,参数iBinder是Service的onBind方法返回的IBinder 对象(在步骤3中我们返回的是MyIBinder对象,所以获得的也是MyIBinder对象,我们就可以通过调用MyBinder对应的方法来获得我们需要的数据)。
onServiceDisconnected:在断开绑定,或者service被杀死时执行。
步骤6:实例化Intent对象,绑定Service,需要传递给Service的信息通过Intent传过去。
Service的代码如下:
public class MySevice extends Service {
private MyIBinder iBinder;
public MySevice(){
iBinder = new MyIBinder();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return iBinder;
}
public class MyIBinder extends Binder{
public String getName(){
return "From Service Info";
}
}
}
调用Service的代码如下:
public class MainActivity extends Activity {
private TextView mTextView;<span style="white-space:pre"> </span>// 显示Service传递过来信息的控件
private Button mStartButton;<span style="white-space:pre"> </span>// 绑定Service的按钮
@Override
protected void onCreate(Bundle sav