android aidl导入

dor*_*nsl 4 import android aidl

我正在尝试将android.content.Context导入AIDL文件,但是eclipse无法识别它.

这是我的代码:

package nsip.net;

import android.content.Context; // error couldn't find import for class ...

interface IMyContactsService{

void printToast(Context context, String text);

}
Run Code Online (Sandbox Code Playgroud)

谁能帮我?

Jen*_*ens 7

使用android.content.Context不起作用,因为它没有实现android.os.Parcelable.

但是 - 如果你有一个类(MyExampleParcelable例如)要在AIDL接口(实际实现Parcelable)中传输,则创建一个.aidl文件,MyExampleParcelable.aidl在其中写入:

package the.package.where.the.class.is;

parcelable MyExampleParcelable;
Run Code Online (Sandbox Code Playgroud)


现在,除非你拼命想要跨流程讨论,否则你应该考虑本地服务.

编辑(稍微有用):

这是一个本地服务(即它只会在您自己的应用程序和流程中使用)吗?在这些情况下,通常只需更好地实现绑定并直接返回.

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.
}
Run Code Online (Sandbox Code Playgroud)

基本上,当Activity绑定到您的服务时,它只会将结果转换IBinderSomeService.SomeServiceBinder,调用SomeService.SomeServiceBinder#getSomeService()- 和bang,访问正在运行的Service实例+您可以在其API中调用内容.