Home  >  Q&A  >  body text

android - 实际项目中Activity传递数据最佳实践是?

有个代码优化的问题,假设现在项目有4个Activity依次跳转:A》B》C》D

  1. 有一些公共数据 B,C,D都需要,是用Intent依次传递,还是直接写成public static,或者更好的方法?

  2. 现在D界面进行了一些操作,希望返回到A时(注意:不是D直接跳到A,而是D,C,B回退到A)刷新界面。除了用标志位,更优的方法是?

来,畅所欲言吧

巴扎黑巴扎黑2720 days ago438

reply all(3)I'll reply

  • 阿神

    阿神2017-04-18 09:19:15

    A library that uses event bus, it is recommended to use Eventbus
    Benefits:

    1. Serialization of the passed data is not needed

    2. Use observer pattern to decouple

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:19:15

    1. If it is a constant, you can write a Constant class to store it specifically.
    2. You can open the activity in sequence through startActivityForResult. When returning, you can judge and transfer it in onActivity based on the data in the Intent, requestCode, and resultCode, but the code is definitely not refreshing enough.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:19:15

    The requirements are not particularly clear. The scenario is very similar to the login and registration scenario: click on the login page, forget the password, then complete the operation and return directly to complete the login.

    1. If BC does not have any interaction requirements when returning, and there are no special requirements for A, then just implement launchMode设置成singleInstance or singleTop(处理和前者不一样)结合Activity#onNewIntent(...)

    2. If you have any interaction requirements, just return level by level.

    In addition, you can also use the EventBus library directly (EventBus, otto, RxBus都是可以的, 可以使用EventBus的场景也可以考虑使用LocalBroadcastManager), but you need to consider what happens if A is recycled by the system.

    p.s. Just eliminate the need for static global methods....

    reply
    0
  • Cancelreply