基本步骤
remoteService
1、生成aidl文件(先生成java的接口文件,修改后缀名为aidl,去掉public)
2、定义业务服务StudentQueryService及其内部类StudentQueryBinder
3、实现StudentQueryService的onBind()和query()
4、在manifest中配置服务信息
=====================================================
实现的代码
1、生成aidl文件
interface StudentQuery {
String queryStudent(int number);
}
2、定义业务服务StudentQueryService及其内部类StudentQueryBinder
public class StudentQueryService extends Service {
private final class StudentQueryBinder extends StudentQuery.Stub{
public String queryStudent(int number) throws RemoteException {
return query(number);
}
}
}
3、实现StudentQueryService的onBind()和query()
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private String query(int number){
if(number > 0 && number < 4){
return names[number - 1];
}
return null;
}
4、在manifest中配置服务信息
<service android:name=".StudentQueryService">
<intent-filter >
<action android:name="com.peter.remoteservice.queryinfo"/>
</intent-filter>
</service>
==========================================================
remoteServiceClient的基本操作和实现代码
基本操作
1、新建工程和Activity, copy刚才的aidl文件到src下
2、在Activity中添加StudentQuery属性,新建内部类StudentConnection
3、实现onCreate() onDestroy()、按钮处理事件、业务逻辑方法等
----------------------------------------------------------------------------------------------------
实现代码
2、在Activity中添加StudentQuery属性,新建内部类StudentConnection
private StudentQuery studentQuery;
private final class StudentConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder service) {
studentQuery = StudentQuery.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName name) {
studentQuery = null;
}
}
3、实现onCreate() onDestroy()、按钮处理事件、业务逻辑方法等
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
numberText = (EditText) this.findViewById(R.id.number);
resultView = (TextView) this.findViewById(R.id.resultView);
Intent intent = new Intent("com.peter.remoteservice.queryinfo");
bindService(intent, conn, BIND_AUTO_CREATE);
}
public void queryStudent(View v) {
String number = numberText.getText().toString();
int num = Integer.valueOf(number);
try {
resultView.setText(studentQuery.queryStudent(num));
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}