我正在使用 ResultReceiver 来允许服务将数据传递给活动。我在比较通过 IPC 发送的意图时遇到了一些困难,看起来对象正在发生变化,因此无法使用标准哈希码(.equals)比较进行比较。我创建了一些将重现该场景的示例代码:
我的活动.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!");
}
}
}
}
我的服务.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;
}
}
如果要运行此服务,请不要忘记在清单中注册服务。
所以意图是来回发送的,过程中没有改变,但我的活动坚持这两个引用不同。这里发生了什么?