android开发aidl使用

最近写了一个aidl,发现有很多忘记了,感觉还是好记性不如烂笔头呀.特此记录下以便以后使用参考

一,创建service和client端,可以是二个不同的APP,也可以在同一个应用中使用二个进程.本文通过创建二个应用实现.aidl一般int ,long , boolean , float ,double, String ,和序列化对象

1,服务端创建序列化对象实现序列号接口

package com.test.aidldemo;

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

public class BookBean implements Parcelable {
    private String book_name;
    private String author;
    public BookBean (String bookName,String author){
        this.book_name = bookName;
        this.author = author;
    }
    public String getBook_name() {
        return book_name;
    }

    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    protected BookBean(Parcel in) {
        book_name = in.readString();
        author = in.readString();
    }

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

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

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(book_name);
        parcel.writeString(author);
    }
}

2,创建同序列号相同的aidl类,包名必须相同否则会报无法找到序列号对象

// BookBean.aidl
package com.test.aidldemo;
parcelable BookBean;

 

3,创建序列号管理接口,导入序列化对象包名

// IBookManager.aidl
package com.test.aidldemo;
import com.test.aidldemo.BookBean;
// Declare any non-default types here with import statements
import com.test.aidldemo.IOnNewBookArrivedListener;
interface IBookManager {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
     List<BookBean> getBookList();

     void addBook(in BookBean book);

     void register(IOnNewBookArrivedListener listener,in int priority);
     void unregister(IOnNewBookArrivedListener listener);
}



// IOnNewBookArrivedListener.aidl
package com.test.aidldemo;
import com.test.aidldemo.BookBean;
// Declare any non-default types here with import statements

interface IOnNewBookArrivedListener {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
   boolean onNewBookArried(in BookBean book);
}

4,服务端创建service并清单文件中配置

package com.test.aidldemo;

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 androidx.annotation.Nullable;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class AidlService extends Service {
    private AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    private final CopyOnWriteArrayList<BookBean> mBookList = new CopyOnWriteArrayList<>();
    private RemoteCallbackList<IOnNewBookArrivedListener> mListListener = new RemoteCallbackList<>(); //由于AIDL重新创建对象造成无法注销掉bind,所以使用RemoteCallbackList
    @Override
    public void onCreate() {
        super.onCreate();
        mBookList.add(new BookBean("C++","zhangyi"));
        mBookList.add(new BookBean("C#","xiaoming"));
        new Thread(new WorkThread()).start();
    }

    private class WorkThread implements Runnable{
        @Override
        public void run() {
            while (!atomicBoolean.get()) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                BookBean bookBean = new BookBean("C", "小米");
                mBookList.add(bookBean);
                int count = mListListener.beginBroadcast();
                for (int i = 0; i < count; i++) {

                    IOnNewBookArrivedListener listener = mListListener.getBroadcastItem(i);
                    try {
                        if (listener != null) {
                            listener.onNewBookArried(bookBean);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                }
                mListListener.finishBroadcast();    //完成通知
            }
        }
    }



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

    private Binder mBinder = new IBookManager.Stub() {
        @Override
        public List<BookBean> getBookList() throws RemoteException {
            return mBookList;
        }

        @Override
        public void addBook(BookBean book) throws RemoteException {
            mBookList.add(book);
        }

        @Override
        public void register(IOnNewBookArrivedListener listener, int priority) throws RemoteException {
//            synchronized (mListenerList) {
//                if (!mListenerList.containsKey(priority)) {
//
//                    mListenerList.put(priority,listener);
//                }
//            }
            mListListener.register(listener);
        }

        @Override
        public void unregister(IOnNewBookArrivedListener listener) throws RemoteException {
//            synchronized (mListenerList) {
//                if (mListenerList.containsValue(listener)) {
//                    for (Map.Entry<Integer,IOnNewBookArrivedListener> entry:mListenerList.entrySet()){
//                        if (entry.getValue().equals(listener)){
//                            mListenerList.remove(entry.getKey());
//                            break;
//                        }
//                    }
//                }
//            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        atomicBoolean.set(true);
    }
}

清单文件配置
 <service android:name="com.test.aidldemo.AidlService">
            <intent-filter >
                <action android:name="com.test.aidldemo.AidlService"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>

 

二,1,客户端直接拷贝服务端aidl文件

 

修改BookBean.aidl包名同BookBean的包名相同

// BookBean.aidl
package com.test.aidlclient;
parcelable BookBean;

 

2,启动服务端server,实现AIDL通信

package com.test.aidlclient;

import androidx.appcompat.app.AppCompatActivity;

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.util.Log;

import com.test.aidldemo.IBookManager;
import com.test.aidldemo.IOnNewBookArrivedListener;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private IBookManager bookManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setPackage("com.test.aidldemo");
        intent.setAction("com.test.aidldemo.AidlService");
        bindService(intent,mCon, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mCon =  new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            bookManager = IBookManager.Stub.asInterface(iBinder);
            try {
                List<BookBean> bookList = bookManager.getBookList();
                for (BookBean book : bookList) {
                    Log.d(TAG,book.getBook_name()+"\n"+book.getAuthor());
                }
                bookManager.register(listener,10);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private IOnNewBookArrivedListener listener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public boolean onNewBookArried(BookBean book) throws RemoteException {
            Log.d(TAG,"Book:"+book.getBook_name()+"\n author:"+book.getAuthor());
            return false;
        }
    };

    @Override
    protected void onDestroy() {
        if (bookManager != null && bookManager.asBinder().isBinderAlive()){
            try {
                bookManager.unregister(listener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mCon);
        super.onDestroy();
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值