android aidl import

2019-02-23 12:58发布

问题:

I'm trying to import android.content.Context to AIDL file but eclipse doesn't recognize it..

here's my code:

package nsip.net;

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

interface IMyContactsService{

void printToast(Context context, String text);

}

Can anyone help me?

回答1:

Using android.content.Context isn't going to work since it doesn't implement android.os.Parcelable.

However - ff you have a class (MyExampleParcelable for instance) that you want to transfer in an AIDL interface (& that actually implements Parcelable) you create an .aidl file, MyExampleParcelable.aidl in which you write:

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

parcelable MyExampleParcelable;


Now, unless you desperately want to talk across processes you should consider local services.

Edit(slightly more helpful):

Is this a local service (i.e. it will only be used inside your own application & process)? In these cases it's usually just better to implement a binder and return that directly.

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.
}

Basically, when the Activity has bound to your service it will simply cast the resulting IBinder to SomeService.SomeServiceBinder, call SomeService.SomeServiceBinder#getSomeService() - and bang, access to the running Service instance + you can call stuff in its API.