学习使用Android Studio编写AIDL的Demo

来源:互联网 发布:linux运维门槛低 编辑:程序博客网 时间:2024/06/10 06:55

最近在做android的时候需要用到AIDL,在网上搜资料发现还是一头雾水,基本都是Eclipse做的。所以就自己摸索着用Android Studio写了一个小demo。

我想使用aidl在一个app中调用另一个app的方法。实现的功能很简单,类似一个欢乐斗地主的app要买豆时调用另一个app的支付功能。

-首先新建一个支付的module,我取名为zhifubao:在里面新建一个aidl的文件,取名为Iservice,这个时候as会自动生成一个aidl的包,里面有一个Iservice.aidl的文件,在里面加一个callPay()方法,代码如下:
这里写图片描述

// Iservice.aidlpackage com.leehour.aidldemo;// Declare any non-default types here with import statementsinterface Iservice {    /**     * Demonstrates some basic types that you can use as parameters     * and return values in AIDL.     */    boolean callPay(String name, String pwd, int money);}

-随后关键的一步来了:点击Make Project(ctrl+F9),即可在project-zhifubao-build-generated-source-aidl-debug-包名下找到新生成的Iservice.java文件,这个文件不可修改,里面有句代码:

这里写图片描述

public static abstract class Stub extends android.os.Binder implements com.leehour.aidldemo.Iservice

意味着我们在服务里面可以用到Stub类,这里先提一下,后面看具体用法。

-我们再新建一个服务PayService,注意在manifest里面声明(不过如果是使用的as新建的服务,在manifest里面已经自动加上声明了),在服务里面新建我们所要暴露给其他app的方法:pay()

package com.leehour.aidldemo;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.os.RemoteException;public class PaySerivce extends Service {    @Override    public IBinder onBind(Intent intent) {        return new MyBinder();    }    public boolean pay(String name, String pwd, int money) {        System.out.println("name:"+name+"pwd:"+pwd+"money:"+money);        if ("abc".equals(name) && "123".equals(pwd) && money < 5000) {            return true;        } else {            return false;        }    }    private class MyBinder extends Iservice.Stub {        @Override        public boolean callPay(String name, String pwd, int money) throws RemoteException {            return pay(name,pwd,money);        }    }}

此时我们使用到了Stub类,这样我们可以通过新建的MyBinder类继承Stub来创建MyBinder对象,在onBind方法中返回一个MyBinder对象。

-到这里,支付端的app就已经完成了。再新建“欢乐斗地主”的module,在layout里面加一个按钮:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="买豆"        android:onClick="click"/></LinearLayout>

-新建一个aidl文件Iservice.aidl,包名要和上面的支付app的包名一致,这里都取为:”com.leehour.aidldemo”,里面的代码也和上面的app一致:
这里写图片描述

// Iservice.aidlpackage com.leehour.aidldemo;// Declare any non-default types here with import statementsinterface Iservice {    /**     * Demonstrates some basic types that you can use as parameters     * and return values in AIDL.     */    boolean callPay(String name, String pwd, int money);}

-随后也点击Make Project(ctrl+F9),此时在debug文件夹下也会生成Iservice.java文件。
这里写图片描述

在mainActivity中加入如下代码:

package com.leehour.happydoudizhu;import android.app.Activity;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.util.Log;import android.view.View;import android.widget.Toast;import com.leehour.aidldemo.Iservice;/** * Created by leehour on 2016/9/9. */public class MainActivity extends Activity {    private MyConn conn;    private Iservice iservice;    private Intent intentService=new Intent();    final String BOUNDSERVICE_PACKAGE = "com.leehour.aidldemo";    final String BOUNDSERVICE_CLASS = ".PaySerivce";    //Bound Service Connection    /*private ServiceConnection conn = new ServiceConnection() {        public void onServiceConnected(ComponentName name, IBinder boundService) {            iservice = Iservice.Stub.asInterface(boundService);        }        public void onServiceDisconnected(ComponentName name) {        }    };*/    private class MyConn implements ServiceConnection {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            iservice = Iservice.Stub.asInterface(iBinder);        }        @Override        public void onServiceDisconnected(ComponentName componentName) {        }    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        intentService.setClassName(BOUNDSERVICE_PACKAGE,                BOUNDSERVICE_PACKAGE + BOUNDSERVICE_CLASS);        conn=new MyConn();        bindService(intentService, conn, BIND_AUTO_CREATE);    }    public void click(View view) {        try {            boolean result = iservice.callPay("abc", "123", 100);            if (result) {                Toast.makeText(getApplicationContext(), "买豆成功", Toast.LENGTH_LONG).show();            } else {                Toast.makeText(getApplicationContext(), "买豆失败", Toast.LENGTH_LONG).show();            }        } catch (RemoteException e) {            e.printStackTrace();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        unbindService(conn);    }}

其中BOUNDSERVICE_PACKAGE和BOUNDSERVICE_CLASS是第一个app的包名和服务的类名,这里我们使用的是MyConn直接实现的ServiceConnection借口,也可以使用上面注释里面的方法。

这样就做好了两个app,将第一个部署到模拟机上,再部署第二个,点击“买豆”按钮,就会弹出吐司“买豆成功”,大功告成!

工程如下:android studio aidldemo

0 0