首页 » Android » 正文

aidl书籍管理(无取消注册)

  1. book
public class Book implements Parcelable {
    public int booId;
    public String bookName;

    public Book(int booId, String bookName){
        this.booId=booId;
        this.bookName=bookName;
    }
    @Override
    public int describeContents() {
        return 0;
    }

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

    public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>(){

        @Override
        public Book createFromParcel(Parcel source) {
            return new Book(source);
        }

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

    private Book(Parcel in){
        booId=in.readInt();
        bookName=in.readString();
    }

    @Override
    public String toString() {
        return "bookId: "+booId +" bookName: "+bookName;
    }
}
  1. 服务端
/**
 *
 * @author xuanqis
 * 服务端服务,进行书籍的管理,无法取消注册监听器
 */
public class BookManagerServer extends Service {

    private static final String TAG = "BookManagerServer";

    /**
     * 判断服务是否已经死亡的原子变量,用在添加书籍的线程
     */
    private AtomicBoolean isServiceDestroy = new AtomicBoolean(false);
    /**
     * 书籍的列表,这里虽然是CopyOnWriteArrayList,但是在传递到客户端的过程中会转化为ArrayList
     * CopyOnWriteArrayList不是ArrayList的子类
     */
    private CopyOnWriteArrayList<Book> mBookLists = new CopyOnWriteArrayList<>();
    /**
     * 这里需要改,这个并不能实现移除监听器的功能,因为客户端监听器在服务端生成的是代理
     */
    private CopyOnWriteArrayList<IOnNewBookArrivedListener> mListeners =
            new CopyOnWriteArrayList<>();

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

        @Override
        public void addBook(Book book) throws RemoteException {
            mBookLists.add(book);
        }

        @Override
        public void registerListener(com.example.a2.aidl.IOnNewBookArrivedListener listener) throws RemoteException {
            if (!mListeners.contains(listener)){
                mListeners.add(listener);
            }
            else {
                Log.i(TAG, "已经存在了");
            }
            Log.i(TAG, "监听器的个数:"+mListeners.size());
        }

        @Override
        public void unRegisterListener(com.example.a2.aidl.IOnNewBookArrivedListener listener) throws RemoteException {
            if (mListeners.contains(listener)){
                mListeners.remove(listener);
            }
            else {
                Log.i(TAG, "不存在这个监听器");
            }
            Log.i(TAG, "监听器的个数:"+mListeners.size());
        }
    };
    public BookManagerServer() {
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        mBookLists.add(new Book(1, "Android"));
        mBookLists.add(new Book(2, "IOS"));
        new Thread(new ServerWorker()).start();
    }


    private void onNewBookArrived(Book book )throws RemoteException{
        mBookLists.add(book);
        Log.d(TAG, "开始逐个进行监听器的开启:"+mListeners.size());
        for (IOnNewBookArrivedListener listener : mListeners) {
            Log.d(TAG, "告知监听器:"+listener);
            listener.onNewBookArrived(book);
        }
    }

    /**
     * 每隔5s添加一本书籍
     */
    private class ServerWorker implements Runnable{
        @Override
        public void run() {
            while(!isServiceDestroy.get()){
                try{
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int bookId = mBookLists.size()+1;
                Book newBook = new Book(bookId, "new Book# "+bookId);
                try{
                    onNewBookArrived(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
  1. 客户端活动
/**
 * @author xuanqis
 * 客户端活动,能够增加书籍,查询书籍列表,在新书到达时接受书籍信息
 */
public class BookManagerActivity extends AppCompatActivity {

    private static final String TAG = "BookManagerActivity";
    //新书到达的消息what
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;

    private IBookManager bookManager;
    /**
     * 在主线程处理消息
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.d(TAG, "新来了一本书:" + msg.obj);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bookManager = IBookManager.Stub.asInterface(service);
            try {
                List<Book> list = bookManager.getBookList();
                Log.i(TAG, "query book list, list type:" + list.getClass());
                Log.i(TAG, "query book list, list type:" + list.toString());
                Book book = new Book(3, "Android进阶");
                bookManager.addBook(book);
                Log.d(TAG, "加入:" + book);
                list = bookManager.getBookList();
                Log.d(TAG, "书单:" + list.toString());
                bookManager.registerListener(mIOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bookManager = null;
            Log.e(TAG, "连接关闭.");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        //绑定客户端和服务端
        Intent intent = new Intent(this, BookManagerServer.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        //这里理论上个取消注册,但是实际上传到服务端的跟原先生成的不是一个对象,所以不可能
        //通过remove来取消注册
        if (bookManager != null && bookManager.asBinder().isBinderAlive()) {
            try {
                bookManager.unRegisterListener(mIOnNewBookArrivedListener);
                Log.d(TAG, "解除注册" + bookManager);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //解除绑定
        unbindService(mServiceConnection);
        super.onDestroy();
    }


    /**
     * 新书到达的监听器,在客户端进程执行
     */
    private IOnNewBookArrivedListener mIOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            //这里的book是放在obj里面,要注意的是obj的跨进程只能支持系统设置的Parcelable类
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, book).sendToTarget();
        }
    };

}
  1. aidl
// Book.aidl
package com.example.a2.aidl;

parcelable Book;

// IBookManager.aidl
package com.example.a2.aidl;

import com.example.a2.aidl.Book;
import com.example.a2.aidl.IOnNewBookArrivedListener;
interface IBookManager {
    List<Book> getBookList();

    void addBook(in Book book);

    void registerListener(IOnNewBookArrivedListener listener);
    void unRegisterListener(IOnNewBookArrivedListener listener);
}


// IOnNewBookArrivedListener.aidl
package com.example.a2.aidl;

import com.example.a2.aidl.Book;

interface IOnNewBookArrivedListener {
    void onNewBookArrived(in Book book);
}
赞 (0)

发表评论