Android開發-解決 AIDL 中找不到couldn't find import for class錯誤


最近在使用AIDL做IPC的時候,在處理復雜的數據類型的時候,編譯器總是報couldn't find import for class錯誤,所以在這里總結下AIDL使用的時候的一些注意事項,希望對你能有所幫助。

Android 中進程間通信使用了 AIDL 語言,但是支持的數據類型有限:

1.Java的簡單類型(int、char、boolean等)。不需要導入(import)。

2.String和CharSequence。不需要導入(import)。

3.List和Map。但要注意,List和Map對象的元素類型必須是AIDL服務支持的數據類型。不需要導入(import)。

4.AIDL自動生成的接口。需要導入(import)。

5.實現android.os.Parcelable接口的類。需要導入(import)。

其中后兩種數據類型需要使用import進行導入。

剛開始想當然的以為傳遞Object只要實現了Parcelable接口在AIDL文件中導入即可, 然后編譯器馬上打敗了我的天真,couldn't find import for class!!!,好吧還是老老實實的去看文檔吧。AIDL文檔鏈接

 

解決這個錯誤的步驟如下:

1.確保你的類已經實現了 Parcelable接口

2.實現writeToParcel方法,將對象的當前狀態寫入 Parcel

3.添加一個叫 CREATOR 的靜態字段,它實現了 Parcelable.Creator

4.最后創建一個對應的*.aidl文件去聲明你的Parcelable類

例如

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;
import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }

        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };

    public Rect() {
    }

    private Rect(Parcel in) {
        readFromParcel(in);
    }

    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM