在Android中使用共享首选项 [英] Using Shared Preferences in Android
问题描述
我有三个活动,A,B&C.其中A是启动活动,B包含由用户ID和密码文本字段以及一个用于登录的按钮组成的登录屏幕.当我单击登录时,将带我进入欢迎屏幕,并在屏幕C上显示用户名.
I have three activities, A, B & C. Where A is a splash Activity and B Contains Login screen which consist of user Id and Password Text Field and one button to login. When I click on login it takes me to the welcome screen shows the user name on screen C.
在这里,我想实现共享首选项",以便我可以存储用户的用户名和密码,从而使用户不必再次插入用户名和密码.再次启动屏幕后,用户直接进入欢迎屏幕.
Here I want to implement Shared Preference so that I can store the userid and password for the user so that user doesn't have to insert the userid and password again & again and after splash screen user directly go to welcome screen.
我阅读了一些有关共享首选项的文档,我知道共有两种类型的共享首选项,一种是活动级别,另一种是应用程序级别.
I read several documents about the shared preference and I came to know that there are two types of shared preference one is activity level and other one is application level.
我该如何实现?
推荐答案
这相对容易.您可以将用户名和密码直接存储在SharedPreference中,如下所示:
This is relatively easy. You can store the username and password directly in the SharedPreference as follows:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
p.edit().putString("username", username).commit();
p.edit().putString("password", password).commit(); //SECURITY HAZARD: read below...
然后您可以像这样检索它:
Then you can retrieve it like this:
String username = p.getString("username", "");
String password = p.getString("password", "");
这样做的问题是密码在全球范围内可用.您需要一种防止他人查看的方法.这样做的方法是在保存密码时对其进行加密,并在使用对称密钥加载密码时对其进行解密.这是有关加密的教程: http://android.voxisland.com/code_examples/How_to_encrypt_and_decrypt_strings.rhtml
The issue when doing this is that the password is available globally. You need to have a way to prevent others from viewing it. The way you do this is by encrypting the password when you save it and decrypting it when you load it using a symmetric key. Here's a tutorial on encryption: http://android.voxisland.com/code_examples/How_to_encrypt_and_decrypt_strings.rhtml
让我知道这是否对您有帮助.
Let me know if this helps you at all.
以马内利
这篇关于在Android中使用共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!