当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Bundle putIBinder getIBinder deprecated

问题描述:

It seems that Bundle has deprecated putIBinder and getIBinder which I thought was very useful for passing binders (through Bundles) over to my service. Since these are deprecated, is there an alternative to this?

I really need to pass an IBinder object over to my service, and I thought the Bundle approach was the easiest (best) solution for this.

Thanks,

J

网友答案:

Posting this which may help someone who deals with binders. I use this approach, still works with Bundle

// write
bundle.putParcelable(key, new ParcelableBinder(binder));
// read
ParcelableBinder value = bundle.getParcelable(key);
IBinder binder = binder == null ? null : value.getBinder();
// or with possible NPE
IBinder binder = bundle.<ParcelableBinder>getParcelable(key).getBinder()

public static class ParcelableBinder implements Parcelable {

    IBinder mBinder;

    public ParcelableBinder(IBinder binder) {
        mBinder = binder;
    }

    private ParcelableBinder(Parcel in) {
        mBinder = in.readStrongBinder();
    }

    public IBinder getBinder() {
        return mBinder;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStrongBinder(mBinder);
    }

    public static final Creator<ParcelableBinder> CREATOR = new Creator<ParcelableBinder>() {
        @Override
        public ParcelableBinder createFromParcel(Parcel in) {
            return new ParcelableBinder(in);
        }

        @Override
        public ParcelableBinder[] newArray(int size) {
            return new ParcelableBinder[size];
        }
    };
}
网友答案:

No need to use Bundles to pass IBinders across services (I can't even see the Bundle.{put,get}IBinder methods you mention in the javadoc).

You can use IBinder objects directly in AIDL, after you import them. For example, if you want to pass a reference to an IOtherService into a method on IService, then IService.aidl could look like this:

package com.yourpackage;

import com.yourpackage.IOtherService;

interface IService {
   void doSomething(IOtherService service);
}
网友答案:

Would using implementation of Parcelable instead be applicable in your case (Bundle is just an implementation of Parcelable anyways)?

Check out this post on Bundle v Parcelable: Passing a custom Object from one Activity to another Parcelable vs Bundle

分享给朋友:
您可能感兴趣的文章:
随机阅读: