zgq105 / blog

2 stars 0 forks source link

Android AIDL使用总结 #66

Open zgq105 opened 5 years ago

zgq105 commented 5 years ago

image

1.什么是AIDL?作用?

AIDL是Android Interface Definition Language的缩写,表示安卓接口定义语言;其主要作用就是跨进程间的一种通信机制。

2.如何定义AIDL

2.1 定义AIDL文件

//创建接口文件:PersonController.aidl

// PersonController.aidl
package com.ch.android.demo4;

// Declare any non-default types here with import statements
import com.ch.android.demo4.Person;

interface PersonController {

   List<Person> getPersonList();
}

//接口使用到的实体类文件:Person.aidl

// Person.aidl
package com.ch.android.demo4;

parcelable Person;

2.2 定义服务端

定义完AIDL文件之后,手动编译项目;然后创建服务端Service。代码如下: //服务端Service

package com.ch.android.demo4;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;

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

/**
 * Created by zgq on 2019/6/19 16:17
 */
public class PersonService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return new PersonStub();
    }
    public synchronized ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
        return null;
    }

    private static final class PersonStub extends PersonController.Stub {

        @Override
        public List<Person> getPersonList() throws RemoteException {
            //测试数据
            List<Person> list = new ArrayList<>();
            Person person = new Person("zgq");
            list.add(person);
            return list;
        }
    }
}

//服务端使用到的实体类

package com.ch.android.demo4;

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

/**
 * Created by zgq on 2019/6/19 16:11
 */
public class Person implements Parcelable {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    protected Person(Parcel in) {
        name = in.readString();
    }

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

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
    }
}

//清单文件中注册

<service
            android:name=".PersonService"
            android:process=":remote">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <action android:name="com.ch.android.PersonService"/>
            </intent-filter>
        </service>

AIDL接口中小知识点: