[Private] Android AIDL Demo

2018-08-03  本文已影响22人  赶时间的闹钟

1. Create AIDL file

User.aidl: defind the entity for aidl
ICallback.aidl: defind the callback, only for aidl
IManager.aidl: defind the main aidl interface for usage

// User.aidl: Must to specify the full package name
package com.anter.aidlpractice;

parcelable User;



// ICallback.aidl
package com.anter.aidlpractice;

import com.anter.aidlpractice.User;

interface ICallback {
       void onCallBack(in User user);
}


// IManager.aidl
// Declare any non-default types here with import statements
package com.anter.aidlpractice;

import com.anter.aidlpractice.User;
import com.anter.aidlpractice.ICallback;
interface IManager {

        String basicTypesToString(int anInt, long aLong, boolean aBoolean, float aFloat,
                double aDouble, String aString);

        User updateUser(in User user);

        void managerCallback(ICallback callback);

}

2. Define User entity

Impliment the aidl data entity User.aidl

package com.anter.aidlpractice;

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

/**
 * @author Anter
 * @date 2018/3/30.
 */

public class User implements Parcelable {

    private String name;
    private String gender;
    private int age;
    private boolean isChinese;

    public User(String name, String gender, int age, boolean isChinese) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.isChinese = isChinese;
    }

    public User() {
    }

    protected User(Parcel in) {
        name = in.readString();
        gender = in.readString();
        age = in.readInt();
        isChinese = in.readByte() != 0;
    }

    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 String toString() {
        return "name:" + name
                + "gender:" + gender
                + "age:" + age
                + "isChinese:" + isChinese;
    }


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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeString(gender);
        parcel.writeInt(age);
        parcel.writeByte((byte) (isChinese ? 1 : 0));
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

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

    public boolean isChinese() {
        return isChinese;
    }

    public void setChinese(boolean chinese) {
        isChinese = chinese;
    }

}

3. Build project

To produce ICallback.java adn IManager.java

produce fles.png

4. Create AIDL Service

Create AIDL service and run on another process by add android:process=":remote" in AndroidManifest.xml

package com.anter.aidlpractice;

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

/**
 * @author Anter
 * @date 2018/3/30.
 */

public class ManagerService extends Service {

    private RemoteCallbackList<ICallback> callbackList = new RemoteCallbackList<>();

    private Binder binder = new IManager.Stub() {
        @Override
        public String basicTypesToString(int anInt,
                                         long aLong,
                                         boolean aBoolean,
                                         float aFloat,
                                         double aDouble,
                                         String aString) throws RemoteException {
            return "anInt:" + anInt
                    + "aLong:" + aLong
                    + "aBoolean:" + aBoolean
                    + "aFloat:" + aFloat
                    + "aDouble:" + aDouble
                    + "aString:" + aString;
        }

        @Override
        public User updateUser(User user) throws RemoteException {
            user.setName("Back " + user.getName());
            user.setGender("Back " + user.getGender());
            user.setAge(100 + user.getAge());
            user.setChinese(!user.isChinese());
            return user;
        }

        @Override
        public void managerCallback(ICallback callback) throws RemoteException {
            callbackList.register(callback);
            final int n = callbackList.beginBroadcast();
            for (int i = 0; i < n; i ++) {
                callbackList.getBroadcastItem(i).onCallBack(new User("小武", "男", 12, true));
            }
            callbackList.finishBroadcast();
            callbackList.unregister(callback);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

}

5. Usage

  1. Binde service
  2. Usage
package com.anter.aidlpractice;

import android.content.ComponentName;
import android.content.Context;
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.util.Log;
import android.view.View;

/**
 * @author Anter
 */
public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";

    private IManager manager = null;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.i(TAG, "onServiceConnected: ");
            manager = IManager.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i(TAG, "onServiceDisconnected: ");
        }
    };

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

        bindService(new Intent(this, ManagerService.class), conn, Context.BIND_AUTO_CREATE);

        setClickListener();
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }

    private void setClickListener() {
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (manager != null) {
                    try {
                        manager.managerCallback(new ICallback.Stub() {
                            @Override
                            public void onCallBack(User user) throws RemoteException {
                                Log.i(TAG, this.getClass().getSimpleName() + "onCallBack: " + user.toString());
                            }
                        });
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                startActivity(new Intent(MainActivity.this, SecondActivity.class));
            }
        });
    }

}

AIDL Demo

上一篇下一篇

猜你喜欢

热点阅读