Is it safe to reuse an intent?

牧云@^-^@ 提交于 2019-12-23 06:56:40

问题


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:


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.



来源:https://stackoverflow.com/questions/16285137/is-it-safe-to-reuse-an-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!