Is it safe to reuse an intent?

2019-06-15 07:55发布

The Android docs define an Intent as "a bundle of information containing an abstract description of an operation to perform". This suggests that you should be able to reuse a single Intent object multiple times if needed, but I haven't seen any examples showing this is the case/ is safe to do. Is there any reason to NOT do the following:

private final Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
...
protected void onCreate(Bundle savedInstanceState) {
  enabledBluetoothIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
  ...
}

and then call startActivityForResult(enableDiscoverableIntent, REQUEST_ENABLE_BT_DISCOVERY) in multiple places in the code? What happens if the same intent is started twice?

1条回答
相关推荐>>
2楼-- · 2019-06-15 08:31

It is completely safe when you want to use it to do the exact same thing, since an Intent is no more than a bunch of data and instructions. If you want to use the same Intent object for different purposes (for example you have a bunch of tabs and try to set the tabs reusing the same intent but changing the activity they'll launch) you have to be more careful, and I'd recommend re-creating a new Intent object for each.

查看更多
登录 后发表回答