AIDL使用

AIDL是Android接口定义语言,用于Android跨进程通信。通常也就运用在service与activity之间。

1、定义aidl接口

默认支持的数据类型包括:基础数据类型、String、CharSequence、List、Map
引用类型需要parcelable定义

// User.aidl
package com.zhucy.aidlservice;
// AIDL中不能直接使用引用类型// 这里定义的User.aidl需要和User.java包名相同
parcelable User;
  • UserManager
// UserManager.aidl 
package com.zhucy.aidlservice; 
// 导入不支持的数据类型
import com.zhucy.aidlservice.User; 
// Declare any non-default types here with import statements
interface  UserManager {  
    List getUserList();  
    void addUser(in User user); 
}  
  • User
package com.zhucy.aidlservice;

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

// 不同进程有着不同的内存区域,所有不能以传递句柄的形式。这里需要序列化与反序列化,这里就要实现Parcelable
// 自动生成的代码只支持in的tag,也就是writeToParcel。如果需要out的tag,也就是读
public class User implements Parcelable{
    public String id;
    public String name;

    public User() {
    }

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

    // CREATOR 反序列化
    public static final Creator CREATOR = new Creator() {
        @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;
    }

    // writeToParcel 序列化
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(name);
    }

    public void readFromParcel(Parcel dest) {
        //读值顺序应当是和writeToParcel()方法中一致的
        id = dest.readString();
        name = dest.readString();
    }
}

2、新建Service

AIDL方法运行在binder线程池中,所以如果耗时操作在Activity中调用时要放入线程中

  • UserService
package com.zhucy.aidlservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


public class UserService extends Service {

    // 线程安全
    private CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();

    // 实现AIDL方法
    // AIDL方法时在线程池中运行的
    // 服务端的方法是运行在Binder线程池中的,所以即使耗时操作也无需开线程,但客户端需要放如线程中运行否则会ANR
    private UserManager.Stub userManager = new UserManager.Stub() {
        @Override
        public List getUserList() throws RemoteException {
            return list;
        }

        @Override
        public void addUser(User user) throws RemoteException {
            list.add(user);
        }
    };


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


    @Override
    public void onCreate() {
        System.out.println("--->onCreate");
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // START_NOT_STICKY 服务终止不自动重启 intent挂起除外
        // START_STICKY 服务关闭自动重启 但intent为null intent挂起除外
        // START_REDELIVER_INTENT 服务关闭自动重启 传递最后一个intent 挂起intent均依次传递
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        System.out.println("--->onDestroy");
        super.onDestroy();
    }
}
  • 清单文件

    
        
        
    

3、Activity调用

package com.zhucy.aidlservice;

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.view.View;

public class MainActivity extends AppCompatActivity {

    private UserManager userManager;
    private int i;

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

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User u = new User();
                u.id = "id:"+i;
                u.name = "name:"+i;
                try {
                    userManager.addUser(u);
                    System.out.println(userManager.getUserList().size());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                i++;
            }
        });

        startService();
    }

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

    private void startService(){
        Intent intent = new Intent();
        intent.setAction("com.zhucy.aidlservice");
        intent.setPackage("com.zhucy.aidlservice");
        startService(intent);// Activity退出service正常运行
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }


    private void unBindService(){
        unbindService(conn);
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            userManager = UserManager.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            userManager = null;
        }
    };

}

你可能感兴趣的:(AIDL使用)