如何将ResultReceiver的子类中的成员变量包含在Parcel读/写过程中?

时间:2014-04-28 16:31:25

标签: android parcelable

关于此问题的答案中的代码Restful API service我已对其进行了测试,但它确实有效。为了我的问题,我已经将它浓缩了一点,这是为了理解类 MyResultReceiver 中的成员变量 mReceiver 如何在Parcel写入过程中幸存下来:

intent.putExtra("receiver", mReceiver); 

和阅读过程:

final ResultReceiver receiver = intent.getParcelableExtra("receiver");

接收器上调用发送方法时,由于没有代码可以看到包裹 mReceiver 成员变量,我希望 mReceiver 为空,但不是,为什么?

完整代码示例:

public class HomeActivity extends Activity implements MyResultReceiver.IReceiver {

    public MyResultReceiver mReceiver;

    public void onCreate(Bundle savedInstanceState) {
        mReceiver = new MyResultReceiver(new Handler());
        mReceiver.setReceiver(this);
        final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, QueryService.class);
        intent.putExtra("receiver", mReceiver);
        intent.putExtra("command", "query");
        startService(intent);
    }
}

public class QueryService extends IntentService {
    protected void onHandleIntent(Intent intent) {
        final ResultReceiver receiver = intent.getParcelableExtra("receiver");
        receiver.send(0, Bundle.EMPTY);
    }
}

public MyResultReceiver extends ResultReceiver {

    private IReceiver mReceiver;

    public MyResultReceiver(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }

    public interface IReceiver {
        public void onReceiveResult(int resultCode, Bundle resultData);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode, resultData);
        }
    }
}

0 个答案:

没有答案