天天看點

android aidl空指針,android Aidl程序間通訊解決空指針異常問題

1,服務端 首先在src下建立一個my.test.service包,在包下建立一個*.aidl檔案(跟接口相類似,但是沒有修飾符) android的aidl工具會自動根據aidl檔案生成對應的java類

android aidl空指針,android Aidl程式間通訊解決空指針異常問題

2,接下來定義一個service服務

android aidl空指針,android Aidl程式間通訊解決空指針異常問題

3 ,在伺服器端的manifest.xml中注冊service

android aidl空指針,android Aidl程式間通訊解決空指針異常問題

伺服器端到此告一段落

接下來是用戶端調用伺服器端的方法

1,把伺服器端的aidl檔案連同包一起拷貝到用戶端的src下

2,定義布局檔案

android aidl空指針,android Aidl程式間通訊解決空指針異常問題

3,在用戶端的mainactivity的java類中

定義一個成員變量 flag 預設為false ,定義一個ServiceConnection 的執行個體對象

public ServiceConnection connect=new ServiceConnection(){

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

bookQuery = IBook.Stub.asInterface(service);  //該方法是處理client與service 連接配接時調用

flag=true;     //當連接配接成功是修改flag為true  (解決nullpoint異常的)

}

@Override

public void onServiceDisconnected(ComponentName name) {

bookQuery = null;

}

在按鈕的點選事件中 加入以下判斷

android aidl空指針,android Aidl程式間通訊解決空指針異常問題
android aidl空指針,android Aidl程式間通訊解決空指針異常問題

當flag為true時才去調用 伺服器端的方法

本人第一次寫部落格,寫的不好還請見諒,如有問題大家可以提出一起讨論