几个概念
1.aidl:android interface defination language 接口定义语言
2.IPC inter process connection 进程间通信
背景:
有一个支付宝只付服务
希望该服务供其他应用程序调用使用
1.支付宝支付服务类代码
主activity略
1①需要把提供服务方法的接口定义为IService .aidl
interface IService {
void callapply();
}、
然后刷新一下工程,在gen目录下自动生成IService.java
②
public class AlipayService extends Service {
@Override
public IBinder onBind(Intent intent) {
System.out.println("支付宝服务绑定了");
return new MyBinder();
}
privateds IService.Stub{
@Override
public void callapply() {
apply();
}
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("支付宝服务解绑了");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public void apply() {
System.out.println("支付现金");
}
}
2.其他程序调用该服务的类
package com.wq.game;
import com.wq.alipay.IService;
import android.app.Activity;
import android.app.IntentService;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
public class MainActivity extends Activity {
IService iService;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bind(View v){
intent=new Intent();
intent.setAction("com.wq.zhifu");
bindService(intent, new Myconn(),BIND_AUTO_CREATE );
}
public void call(View v){
try {
iService.callapply();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class Myconn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
iService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}
}
注意:
在该工程中,也需要把支付宝支付服务下的IService.aidl拷进去