简体   繁体   English

保存实例活动状态以维持用户登录?

[英]Save instance state of activity to maintain user logged in?

I am developing an Android application that has a log in form and should maintain the user logged in. Basically what I have to do is make a request to an API and send the user email and password, that request returns a JSONObject which I manage just fine. 我正在开发一个具有登录表单并应保持用户登录状态的Android应用程序。基本上,我要做的就是向API发出请求并发送用户电子邮件和密码,该请求返回一个JSONObject,我只管理精细。

I have a cookieStore instance and save them into the user preferences through an instance of SharedPreferences , so every time I need the current user credentials I just get them from the preferences. 我有一个cookieStore实例,并通过一个SharedPreferences实例将它们保存到用户首选项中,因此,每当我需要当前用户凭据时,我都会从这些首选项中获取它们。

Thing is, if I close the app on my phone (I think that means to "pause" it, right?) I lost all my data which actually makes sense because I'm never saving the instance state of my activities. 问题是,如果我关闭手机上的应用程序(我认为这意味着“暂停”它,对吧?)我丢失了所有实际上有意义的数据,因为我从未保存活动的实例状态。

My question is: 我的问题是:

What do I need to save into the instance state of my activities in order to maintain the user logged in? 为了保持用户登录状态,我需要保存到活动的实例状态中的什么内容? I could save the preferences? 我可以保存首选项吗? How do I do it? 我该怎么做? And also, is that suppose to be done on the onResume() method of each activity? 而且,是否假设要在每个活动的onResume()方法上完成?

Hope someone can help me with this, I'm just starting to develop in Android. 希望有人可以帮助我,我才刚刚开始使用Android开发。 :) :)

Thanks in advance. 提前致谢。

data saved in SharedPreferences doesn't get lost when you close/destroy your app. 关闭/销毁应用程序时,保存在SharedPreferences中的数据不会丢失。 just check for login details OnResume in the SharedPreferences. 只需在SharedPreferences中检查登录详细信息OnResume。 Don't forget to delete it from SharedPreferences when the user log out. 用户注销时,请不要忘记从SharedPreferences中将其删除。

you could also save datetime of login in SharedPreferences and check it OnResume to see if user is timeout or not. 您还可以将登录的日期时间保存在SharedPreferences中,并在OnResume中对其进行检查,以查看用户是否超时。

If you are using SharedPreferences and you don't want/need to save the current state of your activity you could simply get the values from SharedPreferences(if any) in onResume() method. 如果您使用的是SharedPreferences,并且不想/不需要保存活动的当前状态,则只需在onResume()方法中从SharedPreferences(如果有)中获取值即可。

If you wan't to preserve the state of your activity, you must use the onSaveInstanceState(Bundle outState) method to save your data in the Bundle and in onCreate(Bundle savedInstanceState) to get the data from the Bundle and populate your View's. 如果您不想保留活动状态,则必须使用onSaveInstanceState(Bundle outState)方法将数据保存在Bundle中,并使用onCreate(Bundle savedInstanceState)方法从Bundle中获取数据并填充视图的数据。

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

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