通过研究代码可知,和普通的服务类相比,远程服务类最大的区别就是它拥有一个名为ServiceImpl的成员变量,这个成员变量继承了Stub类,并实现了Stub类的getName和setName方法。这个Stub类就是由 IWxbService.aidl生成的IWxbService.java提供的。我们不用研究其源代码,只用知道它的用法:
第一:让Service的一个成员变量继承Stub,并实现远程接口的方法;
第二:在Service的onBind方法中返回一个Stub子类的实例。
第四步,配置AndroidManifest.xml
加上如下代码:
<service android:name="WxbService">
<intent-filter>
<action android:name="com.dumaisoft.wxbremoteservice.REMOTE_SREVICE"/>
</intent-filter>
</service>
注意action的name为”com.dumaisoft.wxbremoteservice.REMOTE_SREVICE”,这个由开发者保证不重名即可。
第五步,安装app到手机上
安装完成后,你的远程服务就被注册到Binder黑盒子中了,任何客户端只要知道你的远程服务action名称和接口,就可以bind服务,并调用接口。
远程服务调用教程
第一步,创建一个android应用
应用名为WxbRemoteServiceClient,src包中自动生成了com.dumaisoft.wxbremoteserviceclient包。
第二步,引入远程服务的AIDL文件
在src包中创建com.dumaisoft.wxbremoteservice包(为了与服务端的包名相同),然后将上面编写的IWxbService.aidl文件拷贝入此目录。显然,在本工程的gen目录中也生成了IWxbService.java文件。
第三步,编写调用远程服务的代码
代码如下:
package com.dumaisoft.wxbremoteserviceclient;
import com.dumaisoft.wxbremoteservice.IWxbService;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btnBind;
private Button btnSetName;
private Button btnGetName;
private IWxbService serviceProxy; //远程服务的代理
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取远程服务代理
serviceProxy = IWxbService.Stub.asInterface(service);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBind = (Button) this.findViewById(R.id.btnBind);
btnSetName = (Button) this.findViewById(R.id.btnSetName);
btnGetName = (Button) this.findViewById(R.id.btnGetName);
btnBind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent();
//Remote Service Action name
service.setAction("com.dumaisoft.wxbremoteservice.REMOTE_SREVICE");
bindService(service, conn, Service.BIND_AUTO_CREATE);
}
});
btnSetName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
serviceProxy.setName("MyName");
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
btnGetName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
String name = serviceProxy.getName();
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}










