欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Android aidl的使用方法

程序员文章站 2024-01-08 16:40:52
aidl是android中ipc(inter-process communication)方式中的一种,aidl是android interface definition language的缩写(对于...

aidl是android中ipc(inter-process communication)方式中的一种,aidl是android interface definition language的缩写(对于小白来说,aidl的作用是让你可以在自己的app里绑定一个其他app的service,这样你的app可以和其他app交互。)

aidl只是android中众多进程间通讯方式中的一种方式,

aidl和messenger的区别:

  1. messenger不适用大量并发的请求:messenger以串行的方式来处理客户端发来的消息,如果大量的消息同时发送到服务端,服务端仍然只能一个个的去处理。
  2. messenger主要是为了传递消息:对于需要跨进程调用服务端的方法,这种情景不适用messenger。
  3. messenger的底层实现是aidl,系统为我们做了封装从而方便上层的调用。
  4. aidl适用于大量并发的请求,以及涉及到服务端端方法调用的情况

aidl通信的原理:首先看这个文件有一个叫做proxy的类,这是一个代理类,这个类运行在客户端中,其实aidl实现的进程间的通信并不是直接的通信,客户端和服务端都是通过proxy来进行通信的:客户端调用的方法实际是调用是proxy中的方法,然后proxy通过和服务端通信将返回的结果返回给客户端。

1、aidl的作用

aidl是用于android的ipc通讯的,因此可以在一个app内部通讯,也可以创建两个app之间进行通讯。

aidl的职能分配很明确,service作为后台运行作为服务器管理各种交互,client作为客户端请求数据或调用service的方法。

2、aidl的简单使用

1)创建一个aidl文件,直接右键创建就可以了,

package com.example.mytest;

// imyaidlinterface.aidl
package com.example.mytest;
 
// declare any non-default types here with import statements
 
interface imyaidlinterface {
  /**
   * demonstrates some basic types that you can use as parameters
   * and return values in aidl.
   */
  void basictypes(int anint, long along, boolean aboolean, float afloat,
      double adouble, string astring);
  string add(int x , int y);
}

2)选中刚刚建立的 .aidl文件 生产对应的java文件。

androidstudio 可以通过build--》model app 完成

3)编写service的具体对象 实现接口

package com.example.mytest;
import android.app.service;
import android.content.intent;
import android.os.ibinder;
import android.os.remoteexception;
import android.util.log;
public class firstservice extends service {
  public firstservice() {
  }
  private static string tag = "firstservice";
  @override
  public ibinder onbind(intent intent) {
    // todo: return the communication channel to the service.
    //throw new unsupportedoperationexception("not yet implemented");
    log.d(tag,"service on bind");
    return mbinder;
  }
  @override
  public void oncreate() {
    super.oncreate();
    log.d(tag,"oncreate");
  }
  @override
  public int onstartcommand(intent intent, int flags, int startid) {
    log.d(tag,"onstartcommand");
    return start_sticky;
  }
  @override
  public boolean onunbind(intent intent) {
    log.d(tag,"onunbind");
    return super.onunbind(intent);
  }
  @override
  public void ondestroy() {
    super.ondestroy();
    log.d(tag,"ondestroy");
  }
  imyaidlinterface.stub mbinder = new imyaidlinterface.stub(){
    @override
    public void basictypes(int anint, long along, boolean aboolean, float afloat, double adouble, string astring) throws remoteexception {
    }
    @override
    public string add(int x, int y) throws remoteexception {
      log.d(tag,x + "--" + y);
      return string.valueof(x + y);
    }
  };
}

注意:onbund 返回ibinder类型,为了后面的回调会调动

4)确定一下androidmanifest.xml里面的service内容

 <service
      android:name=".firstservice"
      android:enabled="true"
      android:exported="true">
      <intent-filter>
        <action android:name="com.example.mytest.aidl.firstservice"/>
      </intent-filter>
 
    </service>

5)打开服务

 private button btnstartservice; 
  private button btnbindservice;
  
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
 
    initview();
  }
 
  private void initview() {
    tvid = (textview) findviewbyid(r.id.tv_id);
 
    btnstartservice = (button) findviewbyid(r.id.btn_start_service);
    btnstartservice.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view view) {
        intent intent = new intent();
        intent.setpackage("com.example.mytest");
        intent.setaction("com.example.mytest.aidl.firstservice");
        startservice(intent);
      }
    });
 
    btnbindservice = (button) findviewbyid(r.id.btnbindservice);
    btnbindservice.setonclicklistener(new view.onclicklistener() {
      @override
        public void onclick(view view) {
            bind();
        }
    });
  
 
  private void bind(){
    log.d(tag, "bind");
    intent intent = new intent();
    intent.setpackage("com.example.mytest");
    if(controllerconnection != null){
      this.bindservice(intent,controllerconnection,this.bind_auto_create);//绑定服务,建立链接
    }
    else {
      log.d(tag, "controllerconnection != null");
    }
  }
 
  private void unbind(){
    if(controllerconnection != null && myaidlcontroller.asbinder().isbinderalive()){
      try{
        log.d(tag, "this.unbindservice(controllerconnection);");
        this.unbindservice(controllerconnection);
      } catch (exception localexception) {
        log.w(tag, "unbind exception localexception");
      }
    }
  }

在bind的时候是异步的,因此可以通过onserviceconnected()来判断绑定上后的操作。

private serviceconnection controllerconnection = new serviceconnection(){
 
    @override
    public void onserviceconnected(componentname componentname, ibinder ibinder) {
      log.d(tag,"onserviceconnected");
 
      myaidlcontroller = imyaidlinterface.stub.asinterface(ibinder);
      if (myaidlcontroller != null) {
        try {
          log.d(tag, "serviceconnection success");
          toast.maketext(mainactivity.this, "serviceconnection success", toast.length_long).show();
        } catch (exception localexception) {
          log.w(tag, "exception localexception");
        }
      }
    }
 
    @override
    public void onservicedisconnected(componentname componentname) {
      log.d(tag,"onservicedisconnected");
      toast.maketext(mainactivity.this, "onservicedisconnected", toast.length_long).show();
 
      myaidlcontroller = null;
    }
 
    @override
    public void onbindingdied(componentname name) {
      log.d(tag,"onbindingdied");
    }
 
    @override
    public void onnullbinding(componentname name) {
      log.d(tag,"onnullbinding");
    }
  };

6)调用service方法add()

调用的时候需要绑定service方法,上面已经有了,接下来调用就简单了,创建一个button,然后拿到service的控制对象,调用方法add

 btnservicefunc = (button) findviewbyid(r.id.btnservicefunc);
    btnservicefunc.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view view) {
        try {
          log.d(tag, string.valueof( myaidlcontroller.add(1,2)));
        } catch (remoteexception e) {
          e.printstacktrace();
        }
      }
    });

到此这篇关于详解android aidl的使用方法的文章就介绍到这了,更多相关android aidl的使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Android aidl

上一篇:

下一篇: