使用AIDL实现进程通信



一个service应用

public class StudentQueryService extends Service {
private String[] names = {"张飞", "李静", "赵薇"};
private IBinder binder = new StudentQueryBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private String query(int number){
if(number > 0 && number < 4){
return names[number - 1];
}
return null;
}
private final class StudentQueryBinder extends StudentQuery.Stub{
public String queryStudent(int number) throws RemoteException {
return query(number);
} 
}
}
文件末尾改为.aidl后缀
package cn.itcast.aidl;
//AIDL
interface StudentQuery {


String queryStudent(int number);
}


另一个客户端应用  studentQuery = StudentQuery.Stub.asInterface(service);通过AIDL开启一些系统服务,如挂断电话

public class MainActivity extends Activity {
private EditText numberText;
private TextView resultView;
private StudentQuery studentQuery;
private StudentConnection conn = new StudentConnection();


@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 service = new Intent("cn.itcast.student.query");
bindService(service, 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();
}



//注意此处的.sub,因为系统生成的AIDL中的sub继承Binder,故:


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;
}
}
}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值