【随心笔录】Android AIDL使用,实现跨进程通信

来源:互联网 发布:异次元软件站 编辑:程序博客网 时间:2024/05/16 02:00

一、 AIDL

  • 上一篇文章 中,我们通过Bind启动Service,当我们的Service和Activity不在同一进程里面,会报错:java.lang.ClassCastException: android.os.BinderProxy cannot be cast to …
  • 是时候了解了解我们的AIDL了。
  • AIDL(Android Interface Define Language) 是IPC进程间通信方式的一种.用于生成可以在Android设备上两个进程之间进行进程间通信(interprocess communication, IPC)的代码.

二、使用步骤

  • Android studio 很方便就能创建AIDL。
  • 新建一个aidl的文件夹。看图
    新建AIDL
  • 新建的AIDL叫 IMyAidlInterface.aidl。
interface IMyAidlInterface {    //从简,我修改了一下    void start();}
  • 点击运行,图
    点击运行
  • 运行成功,继续。废话不多说,看代码。

    • Service类的代码

      public class AbleService extends Service {public final static String TAG = "AbleService";public AbleService() {}private IBinder aidlInterface = new IMyAidlInterface.Stub() {    @Override    public void start() throws RemoteException {        Log.v(TAG,"IMyAidlInterface实现了进程通信!");    }};@Overridepublic IBinder onBind(Intent intent) {    return aidlInterface ;}}
    • AndroidManifest.xml注册。

      <service        android:name=".service.AbleService"        android:enabled="true"        android:exported="true"        android:process="com.fingerth.able.service">    </service>
    • Activity的代码

      Intent intent = new Intent(this, AbleService.class);    bindService(intent, conn, BIND_AUTO_CREATE);
    private ServiceConnection conn = new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        //这里得到IMyAidlInterface,可以直接调用它的方法,这样就完成了和Service的通信        IMyAidlInterface aidlInterface = IMyAidlInterface.Stub.asInterface(service);        try {            aidlInterface.start();        } catch (RemoteException e) {            e.printStackTrace();        }    }    @Override    public void onServiceDisconnected(ComponentName name) {    }};

三、代码写完,运行looklook

  • 运行当然是成功的了。
  • 运行成功
  • 完。
原创粉丝点击