Android AIDL使用解析

Posted 伟雪无痕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android AIDL使用解析相关的知识,希望对你有一定的参考价值。

一.android AIDL介绍

1.AIDL 即 Android Interface Definition Language,android接口定义语言,,是用于定义服务器和客户端通信接口的一种描述语言,可以拿来生成用于IPC的代码,一般暴露方法给其他应用进行调用的应用称为服务端(server),调用其他应用的方法的应用称为客户端(client),客户端通过绑定服务端的Service来进行交互。

2.AIDL的语法,aidl 文件以.aidl为后缀名,支持的数据类型分为如下几种:
1).八种基本数据类型:byte、char、short、int、long、float、double、boolean
String,CharSequence
2).实现了Parcelable接口的数据类型
3).List 类型。List承载的数据必须是AIDL支持的类型,或者是其它声明的AIDL对象
4).Map类型。Map承载的数据必须是AIDL支持的类型,或者是其它声明的AIDL对象

二.Android AIDL使用步骤

1).创建 .aidl文件,src->New->AIDL->AIDL File
2).实现 .aidl文件中的接口
3).将接口暴露给客户端

注意:服务端和客户端包名需保持一致

三.Android AIDL demo实现

1.服务端demo

1).IUserAidlInterface.aidl

// IUserAidlInterface.aidl
package com.example.aidl;
import java.util.List;

// Declare any non-default types here with import statements
//parcelable  User;

interface IUserAidlInterface 
    void addUser(in User user);
    List<User> getUserList();


2).User.java,实现parceable

package com.example.aidl;

import android.os.Parcel;
import android.os.Parcelable;

public class User implements Parcelable 
    public int id;
    public String name;

    public User(int id, String name) 
        this.id = id;
        this.name = name;
    

    protected User(Parcel in) 
        id = in.readInt();
        name = in.readString();
    

    public static final Creator<User> CREATOR = new Creator<User>() 
        @Override
        public User createFromParcel(Parcel in) 
            return new User(in);
        

        @Override
        public User[] newArray(int size) 
            return new User[size];
        
    ;

    @Override
    public int describeContents() 
        return 0;
    

    @Override
    public void writeToParcel(Parcel parcel, int i) 
        parcel.writeInt(id);
        parcel.writeString(name);
    

3).对于对象引用,需要引入实体类User.aidl

package com.example.aidl;

// Declare any non-default types here with import statements
parcelable  User;

 4).UserService.java

package com.example.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class UserService extends Service 
    private static final String TAG="UserService";

    class UserNative extends IUserAidlInterface.Stub

        List<User> userList=new ArrayList<>();

        @Override
        public void addUser(User user) throws RemoteException 
            Log.e(TAG, "Thread name:" + Thread.currentThread().getName() );
            userList.add(user);
        

        @Override
        public List<User> getUserList() throws RemoteException 
            Log.e(TAG, "Thread name:" + Thread.currentThread().getName() );
            return userList;
        
    

    private UserNative mUserNative=new UserNative();

    @Override
    public IBinder onBind(Intent intent) 
        Log.e(TAG, "Thread name:" + Thread.currentThread().getName() );
        return mUserNative;
    

 manfiest中进行配置

<service
            android:name=".UserService"
            android:enabled="true"
            android:exported="true"></service>

2.客户端demo

1).activity_main.xml,xml布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:gravity="center">

    <Button
        android:id="@+id/binder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="binder service"
        ></Button>

    <Button
        android:id="@+id/adduser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="add user"
        ></Button>

    <Button
        android:id="@+id/getUserList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get userList"
        ></Button>

    <TextView
        android:id="@+id/showUserList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show user List"
        android:textSize="20sp"/>

</LinearLayout>

2).MainActivity.java

package com.example.aidl;

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.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener

    private Button mBinderBtn;
    private Button mAddUserBtn;
    private Button mUserListBtn;
    private TextView mShowUserList;
    private IUserAidlInterface mUserAidlInterface;

    private ServiceConnection mServiceConnection=new ServiceConnection() 
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) 
            mUserAidlInterface= IUserAidlInterface.Stub.asInterface(iBinder);
        

        @Override
        public void onServiceDisconnected(ComponentName componentName) 
            mUserAidlInterface=null;
        
    ;
    
    private IBinder.DeathRecipient mDeathRecipient=new IBinder.DeathRecipient() 
        @Override
        public void binderDied() 
            if (mUserAidlInterface!=null)
                mUserAidlInterface.asBinder().unlinkToDeath(mDeathRecipient,0);
                mDeathRecipient=null;
                binderService();
            
        
    ;

    private void binderService() 
        Intent intent=new Intent();
        intent.setComponent(new ComponentName("com.example.aidl", "com.example.aidl.UserService"));
        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);
    

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initListeners();
    

    private void initListeners() 
        mBinderBtn.setOnClickListener(this);
        mAddUserBtn.setOnClickListener(this);
        mUserListBtn.setOnClickListener(this);
    

    private void initViews() 
        mBinderBtn=findViewById(R.id.binder);
        mAddUserBtn=findViewById(R.id.adduser);
        mUserListBtn=findViewById(R.id.getUserList);
        mShowUserList=findViewById(R.id.showUserList);
    

    @Override
    public void onClick(View view) 
        switch (view.getId())
            case R.id.binder:
                binderService();
                break;
            case R.id.adduser:
                if (mUserAidlInterface!=null)
                    try 
                        mUserAidlInterface.addUser(new User(0001,"linda"));
                        mUserAidlInterface.addUser(new User(0002,"wendy"));
                     catch (RemoteException e) 
                        e.printStackTrace();
                    
                else 
                    Toast.makeText(this,"Please binder service",Toast.LENGTH_LONG).show();
                
                break;
            case R.id.getUserList:
                if (mUserAidlInterface!=null)
                    try 
                        List<User> mUserList=mUserAidlInterface.getUserList();
                        StringBuffer stringBuffer=new StringBuffer();
                        for (User user:mUserList) 
                            stringBuffer.append("id:"+user.id+" name:"+user.name+"---");
                            stringBuffer.append("\\n");
                        
                        mShowUserList.setText(stringBuffer.toString());
                     catch (RemoteException e) 
                        e.printStackTrace();
                    
                
                break;
            default:
                break;

        
    

四.界面显示

 

以上是关于Android AIDL使用解析的主要内容,如果未能解决你的问题,请参考以下文章

Android AIDL使用解析

Android进阶笔记:AIDL内部实现详解

AIDL源码解析inout和inout

Android - IPC之AIDL简介

基于AIDL编程实现Android远程Service服务

基于AIDL编程实现Android远程Service服务