aidl的简单使用

来源:互联网 发布:win10win7共享网络 编辑:程序博客网 时间:2024/06/05 10:23

aidl–进程间的通信(就是2个app之间的通讯)

app1–表示服务的提供者–例如支付包的支付方法,需要对外暴露,让其他app调用其功能

创建一个AliPay.aidl文件–将java的后缀改为aidl

 interface AliPay {     String pay(float menoy);}

注意:aidl中是不能有修饰符的,否则报错

在app1中的AliPayService 中

public class AliPayService extends Service {    @Override    public IBinder onBind(Intent intent) {        return new AliPay.Stub() {            @Override            public String pay(float menoy) throws RemoteException {                return AliPayService.this.pay(menoy);            }        };    }    public String pay(float menoy ){        return "您支付"+menoy+"元成功";    }}

在清单文件中

<service android:name="com.itheima.zhifubao.AliPayService" >            <intent-filter>                <action android:name="alipay.pay" />            </intent-filter>        </service>

这样就将app1中服务的方法通过aidl暴露出去了

app2—表示服务的使用者—例如美团等等,需要使用支付宝的支付功能

使用方法—需要将app1提供的aidl拿到–注意:包名必须与app1中的包名保持一致

在app2的MainActivity中

public class MainActivity extends Activity {    private MyServiceConnection conn;    private AliPay aliPay;    private String pay;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // 开启Alipay服务        Intent service = new Intent("alipay.pay");        conn = new MyServiceConnection();        bindService(service, conn, BIND_AUTO_CREATE);    }    class MyServiceConnection implements ServiceConnection {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            aliPay = AliPay.Stub.asInterface(service);            Toast.makeText(MainActivity.this, "绑定成功", Toast.LENGTH_SHORT)                    .show();        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    }    public void click(View v) {        if (aliPay != null) {            try {                pay = aliPay.pay(123.23f);            } catch (RemoteException e) {                e.printStackTrace();            }            Toast.makeText(MainActivity.this, pay, Toast.LENGTH_SHORT).show();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        if (conn != null)            unbindService(conn);// 解绑操作    }}

注意:给服务绑定后,需要在onDestroy()解除绑定

0 0
原创粉丝点击