安卓绑定服务的思路是:应用程序如果想访问一个服务的方法,它不能直接获取服务的引用,而要通过一个中间人(下面代码里面就是MyBinder对象)进行通信。
package com.example.mytest;
import com.example.mytest.Singer.MyBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainActivity extends Activity {
private MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 绑定服务
*
* @param v
*/
public void bind(View v) {
Intent intent = new Intent(this, Singer.class);
// 第一步:发出绑定服务请求
bindService(intent, new MyConn(), BIND_AUTO_CREATE);
}
private class MyConn implements ServiceConnection {
// 服务成功被绑定时调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
// 第四部 :获得返回的IBinder对象,并且利用这个对象调用服务的功能
myBinder = (MyBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}
/**
* 取消绑定服务
*
* @param v
*/
public void unbind(View v) {
}
/**
* 调用服务进行唱歌
*
* @param v
*/
public void sing(View v) {
// 利用中间者调用服务的方法
myBinder.singASong();
}
}
package com.example.mytest;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class Singer extends Service {
// 第二步 :调用onBind方法
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new MyBinder();
}
/**
* 中间人
*
* @author USER
*
*/
public class MyBinder extends Binder {
// 第三步 :创建MyBinder对象(中间者),并且暴露服务的方法
public void singASong() {
sing();
}
}
@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 sing() {
// 这个方法通过中间者暴露给用户了
System.out.println("开始唱歌了..");
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="bind"
android:text="绑定服务" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="unbind"
android:text="取消绑定服务" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sing"
android:text="唱歌" />
</LinearLayout>