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

10 篇文章 0 订阅
1 篇文章 0 订阅

一、 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实现了进程通信!");
          }
      };
      
      @Override
      public 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

  • 运行当然是成功的了。
  • 运行成功
  • 完。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值