源代码:
1.Activity中的代码
public class MainActivity extends Activity {
//步骤4:在activity中就得到了IBinder对象
SongService.MyBinder binder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bind(View v) {
Intent intent = new Intent(this, SongService.class);
//步骤1: bindService以绑定服务的方式开启服务
// conn:用来建立与服务的连接,不能为空
// BIND_AUTO_CREATE 表示如果没有创建则自动创建
// bindService(service, conn, flags)
bindService(intent, new MyServiceConnection(), BIND_AUTO_CREATE);
}
public void call(View v){
//步骤5:调用IBinder对象的方法
binder.callChange("月亮之上");
}
private class MyServiceConnection implements ServiceConnection {
// 当服务被绑定成功时使用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
//步骤3:获得服务传过来的IBinder对象
binder = (MyBinder) service;
}
// 当服务解除绑定的时候调用,只有在程序被异常终止.
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
2.Service的源代码
public class SongService extends Service{
//当服务绑定成功时调用此方法
@Override
public IBinder onBind(Intent intent) {
System.out.println("服务被成功的绑定了!");
//步骤2:服务绑定成功后返回一个IBinder对象,它将传递给conn的回调方法onServiceConnected
return new MyBinder();
}
public class MyBinder extends Binder{
public void callChange(String name){
change(name);
}
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("服务被创建了");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("服务被销毁了");
}
public void change(String name){
Toast.makeText(this, "把歌曲换成了"+name, 0).show();
}
}
3.记得在配置文件中加上
<service android:name="com.example.testservice.SongService" >