跨应用绑定 Service 要 用 AIDL Android Interface definition language
1.新建一个aidl文件 ,这个接口当作binder返回。(aidl文件简单记忆成与lib的头文件相似,要把它复制到作用它的项目工程中)
interface AppServiceBinder {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
void setData(String dt);
}
2. Service需要返回 IBinder,同一个应用内的service之间用binder,这里也是。
public class AppService extends Service {
public AppService() {
}
@Override
public IBinder onBind(Intent intent) {
return new AppServiceBinder.Stub(){
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public void setData(String dt) throws RemoteException {
AppService.this.data = dt;
}
};
}
...
3.bindService(intent),注意绑定 service时的两个回调函数。onServiceConnected onServiceDisconnected
<span style="white-space:pre"> </span>Intent i = new Intent();
i.setComponent(new ComponentName("com.example.kf8i4fk.appservice","com.example.kf8i4fk.appservice.AppService"));
switch(v.getId()){
case R.id.btnStartAppServ:
<span style="white-space:pre"> </span>break;
//...
case R.id.btnBindAppServ:
bindService(i,this, Context.BIND_AUTO_CREATE);
<span style="white-space:pre"> </span>//...
@Override
public void <span style="color:#ff0000;">onServiceConnected</span>(ComponentName name, IBinder service) {
System.out.println("onServiceConnected");
binder = AppServiceBinder.Stub.asInterface(service);
}
@Override
public void <span style="color:#ff0000;">onServiceDisconnected</span>(ComponentName name) {
System.out.println("onServiceDisconnected");
}
4.通信
注意其它线程不能直接使用ui线程里的控件更新界面,要用消息队列将数据 发送到ui线程,后者再更新