简体   繁体   English

最佳实践:在Android活动之间传递对象

[英]Best practice: passing objects between Android activities

I was wondering what the best practice is to pass objects between activies? 我想知道在活动之间传递对象的最佳做法是什么? My logged out user is on a content item and should be able to get back to this item after the login process. 我注销的用户在内容项上,应该能够在登录过程后返回此项。 Therefore I need to pass the content id between these activities 因此,我需要在这些活动之间传递内容ID

I see 2 basic options: 我看到2个基本选项:

  1. Pass the content-id in the intent as URI (intent.putExtra()) and pass them between activities 将intent中的content-id作为URI(intent.putExtra())传递,并在活动之间传递它们
  2. Save the content-id to the local storage and load it again after login 将content-id保存到本地存储,并在登录后再次加载

Are there any other options and best practices? 还有其他选择和最佳做法吗?

i would suggest using SharedPreferences which is like the option 2. which allows your to get the content-id(or string or json object) after the app is closed. 我建议使用SharedPreferences ,它类似于选项2.它允许您在关闭应用程序后获取content-id(或字符串或json对象)。 you can also encrypt the content-id before put it in sharedPreferences 您还可以在将content-id放入sharedPreferences之前对其进行加密

Besides intent (ram) and local storage (rom/sdcard , including database), i cant see any other option(locally). 除了intent(ram)和本地存储(rom / sdcard,包括数据库),我也看不到任何其他选项(本地)。

Case 1: you need to resume activity after the app is closed 案例1:您需要在应用关闭后恢复活动
you should use local storage 你应该使用本地存储

Case 2: you don't need to resume activity after the app is closed 案例2:应用关闭后您无需恢复活动

 option 1: 0. load the first activity 1. start login_activity (startActivityForResult()) (do not call finish() ) 2. after login is done (call finish()) 3. activity is resumed (if login fail -> redirect to other activity ) option 2: 1. create a public class with a data member to save the content-id/activity class (you may assign singleton design pattern) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM