通过IPC发送意图会改变吗?

时间:2012-06-23 18:19:45

标签: android ipc

我正在使用ResultReceiver来允许服务将数据传递给活动。我在比较通过IPC发送的意图时遇到了一些困难,看起来对象正在发生变化,因此无法使用标准哈希码(.equals)比较进行比较。我已经创建了一些示例代码来重现场景:

MyActivity.java:

public class MyActivity extends Activity {

    private final Handler mHandler = new Handler();
    private Intent serviceIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        MyReceiver receiver = new MyReceiver(mHandler);
        serviceIntent = new Intent(this, MyService.class);
        serviceIntent.putExtra("receiver", receiver);
        startService(serviceIntent);
    }

    public class MyReceiver extends ResultReceiver {

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

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            Intent intent = resultData.getParcelable("intent");
            if(intent.equals(serviceIntent)) {
                Log.d("TEST", "Same intent!");
            } else {
                Log.d("TEST", "Different intents!");
            }
        }

    }

}

MyService.java

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ResultReceiver receiver = intent.getExtras().getParcelable("receiver");
        Bundle b = new Bundle();
        b.putParcelable("intent", intent);
        receiver.send(100, b);
        stopSelf();
        return Service.START_NOT_STICKY;
    }

}

如果您想要运行此服务,请不要忘记在清单中注册该服务。

因此意图来回发送,过程中没有任何变化,但我的活动坚持认为两个参考文献不同。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

Intent intent = resultData.getParcelable("intent")private Intent serviceIntent创建的意图不是同一个对象,即使它们被创建为包含完全相同的数据。当前.equals()函数只检查意图是否是同一个对象;您必须编写自己的.equals()函数,以确定任何适合您的应用程序的定义是否相同。请参阅here