AIDL入门

最常见的aidl的使用就是Service的跨进程通信了,那么我们就写一个Activity和Service的跨进程通信吧。

AIDL的数据传输支持类型有特殊要求,并非所有的数据类型都能像以往一样传递:

支持数据类型如下:

  1. Java 的原生类型
  2. String 和CharSequence
  3. List 和 Map ,List和Map 对象的元素必须是AIDL支持的数据类型; 以上三种类型都不需要导入(import)
  4. AIDL 自动生成的接口 需要导入(import)
  5. 实现android.os.Parcelable 接口的类. 需要导入(import)。

复杂数据类型实现 Parcelable 接口:

由于不同的进程有着不同的内存区域,并且它们只能访问自己的那一块内存区域,所以我们不能像平时那样,传一个句柄过去就完事了——句柄指向的是一个内存区域,现在目标进程根本不能访问源进程的内存,那把它传过去又有什么用呢?所以我们必须将要传输的数据转化为能够在内存之间流通的形式。这个转化的过程就叫做序列化与反序列化

目标:我们实现Activity中创建一个Animal对象,然后把Animal存入到远程Service的List中。然后再取出远程Service的List的数据显示在Activity的TextView中。

创建 Animal.java 。

package com.bsi.aidlcomplexdemo.bean;

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

/**
 * @author QianMang
 * @Date 2018/2/24.
 * @Email [email protected]
 */
public class Animal implements Parcelable{ //需要实现Parcelable接口
    private String name;
    private int age;

    public Animal(String name, int age){
        this.name = name;
        this.age = age;
    }

    public Animal() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

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

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



    protected Animal(Parcel in) {
        this.name = in.readString();
        this.age = in.readInt();
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public Animal createFromParcel(Parcel source) {
            return new Animal(source);
        }

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

创建Animal.aidl

package com.bsi.aidlcomplexdemo.bean;
parcelable Animal;

创建IAnimalInterface.aidl

package com.bsi.aidlcomplexdemo;

import com.bsi.aidlcomplexdemo.bean.Animal;

interface IAnimalInterface {

    void addAnimal(in Animal animal); //添加animal,由于是向服务端内存处写入数据,因此需要in关键字
    List getAnimalList(); //获取animal的List
}

创建AnimalService.java

package com.bsi.aidlcomplexdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.bsi.aidlcomplexdemo.IAnimalInterface;
import com.bsi.aidlcomplexdemo.bean.Animal;

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

/**
 * @author QianMang
 * @Date 2018/2/24.
 * @Email [email protected]
 */
public class AnimalService extends Service {
    List persons;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return personInterface;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        persons = new ArrayList<>();
    }

    IBinder personInterface = new IAnimalInterface.Stub(){

        @Override
        public void addAnimal(Animal animal) throws RemoteException {
            persons.add(animal);
        }

        @Override
        public List getAnimalList() throws RemoteException {
            return persons;
        }
    };
}

创建MainActivity.java

package com.bsi.aidlcomplexdemo.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.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.bsi.aidlcomplexdemo.IAnimalInterface;
import com.bsi.aidlcomplexdemo.R;
import com.bsi.aidlcomplexdemo.bean.Animal;
import com.bsi.aidlcomplexdemo.service.AnimalService;

public class MainActivity extends AppCompatActivity {

    private MyServiceConnection serviceConnection;
    private IAnimalInterface iAnimalInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initService();
        initView();
    }

    private void initView() {
        TextView tv_result = findViewById(R.id.tv_result);
        findViewById(R.id.btn_add).setOnClickListener(view->{
            Animal animal = new Animal("dog", (int) (Math.random() * 100)); //创建一个Animal对象 
            try {

                iAnimalInterface.addAnimal(animal); //将对象添加到Service的List中
                final String results = iAnimalInterface.getAnimalList().toString(); //获取Service的List数据
                tv_result.setText(results);

            } catch (RemoteException e) {
                e.printStackTrace();
            }

        });

    }

    private void initService() {
        Intent intent = new Intent(this, AnimalService.class);
        serviceConnection = new MyServiceConnection();
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

    }

    class MyServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iAnimalInterface = IAnimalInterface.Stub.asInterface(service); 
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection); //解除Service绑定
    }
}

戳我下载

你可能感兴趣的:(android)