使用android.content.Context
不起作用,因爲它不執行android.os.Parcelable
。
但是 - FF你有一個類,你要在AIDL接口傳輸(&真正實現Parcelable
)(MyExampleParcelable
例如)創建一個.aidl
文件,MyExampleParcelable.aidl
在其中寫上:
package the.package.where.the.class.is;
parcelable MyExampleParcelable;
現在,除非你非常想跨過程,你應該考慮本地服務。
編輯(稍微有用):
這是一個本地服務(即它只會被自己的應用程序和進程內使用)?在這些情況下,通常只是更好地實施一個活頁夾並直接返回。
public class SomeService extends Service {
....
....
public class SomeServiceBinder extends Binder {
public SomeService getSomeService() {
return SomeService.this;
}
}
private final IBinder mBinder = new SomeServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void printToast(Context context, String text) {
// Why are you even passing Context here? A Service can create Toasts by it self.
....
....
}
// And all other methods you want the caller to be able to invoke on
// your service.
}
基本上,當Activity
已經綁定到你的服務就會簡單地把導致IBinder
到SomeService.SomeServiceBinder
,打電話SomeService.SomeServiceBinder#getSomeService()
- 和爆炸,訪問正在運行的Service
實例+你可以調用的東西其API。
我將我的aidl文件命名爲一個對象Parcelable與類名不同,因爲Android Studio **抱怨** aidl文件與創建提示中的現有類具有相同的名稱(New - > AIDL文件)。我花了幾個小時,這個相同的錯誤! 聲明對象Parcelable的文件需要與對象具有完全相同的名稱。 – Waffles
@Waffles對於我的測試,這可能是Android studio的一個bug。我創建了一個不同名稱的AIDL文件,但仍然出錯。所以,最後,我使用Refactor => Rename將名稱更改爲與我們的Parcelable java文件相同。 **注意:當我們想要在我們的項目中使用Parcelable文件時我們需要導入AIDL文件 – uestcfei
我發現的另一個技巧是:爲什麼類** android.graphics.Point **也只是實現Parcelable,但如果我們在AIDL中使用它。我們不需要導入它? 因此,我搜索文件名爲**「Point」**的Android源文件,並獲取文件** Point.aidl **。這就是原因。 Google幫助我們編寫Point的AIDL文件,當將Point.java編譯到我們的項目中時,Android Studio自動幫助我們導入它 – uestcfei