繁体   English   中英

如何存储Android的单用户登录数据?

[英]How to store Single user login data for Android?

请参阅有关在Android应用程序中存储单个用户的最佳方法的问答

共享首选项实际上如何工作?

我想做的是:

  • 首次打开应用程序的用户添加了登录ID和密码
  • 下次用户打开应用程序时,将使用先前的ID /密码和数据进行登录。 (我不希望自动登录,因为我的应用程序中的数据会很敏感,因此即使是拿着手机的朋友也无法看到它。)
  • 用户更改此ID /密码的能力

通过共享首选项可以做到这一点吗? 还是我需要使用SQLlite? 我对Android完全陌生,因此,如果您附上有效的代码和说明,我将不胜感激。

只要您愿意在其中存储合理的机密数据,就可以使用共享的首选项进行此操作。 在存储和检索之间,您将需要一些共享代码:

final static String pfName = "com.super.stuff.preffile.name";
final static String pfCodeForID = "com.super.stuff.pf.id";
final static String pfCodeForPassword = "com.super.stuff.pf.passwd";
final static String pfNoStringPresent = "NO-STRING-PRESENT-HERE";

final static pfCodes = MODE_PRIVATE; // See http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int)

要存储信息:

String ID = //whatever;
String password = //whatever;

SharedPreferences settings = context.getSharedPreferences(pfName, pfCodes);
SharedPreferences.Editor editor = settings.edit();
editor.putString(pfCodeForID, ID);
editor.putString(pfCodeForPassword, password);
editor.commit();

要检索信息:

SharedPreferences settings = context.getSharedPreferences(pfName, pfCodes);

String ID = editor.getString(pfCodeForID, pfNoStringPresent);
String password = editor.getString(pfCodeForPassword, pfNoStringPresent);

if (ID.contentEquals(pfNoStringPresent) && password.contentEquals(pfNoStringPresent)) {
     // Handle the case of nothing stored, ie get ID and password
     }

显然,如果用户名和密码都与pfNoStringPresent相同,则此操作将失败!

如果您担心以这种方式存储敏感数据,则需要将其存储在数据库中或以某种方式进行加密。 您需要确定将信息存储在属于向您提供ID信息的人的设备上时,对信息的保护有多重要,从电话中获取此信息对小偷来说有多重要,等等。等等

使用Sqlite,它相当简单。 请遵循以下步骤:

public SQLiteDatabase sampleDB;  
sampleDB =  this.openOrCreateDatabase(TABLE_NAME, MODE_PRIVATE, null);    
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                TABLE_NAME+ "(" + COLUMN_ID
                + " integer primary key autoincrement, " + COLUMN1
                + " text not null,"+ COLUMN2
                + " text not null);");

在这里,我有三个字段,其中column1和column2是具有值“ username”和“ password”的字符串。 创建完成后,您可以根据需要执行查询。

与AccountManager集成,然后使用setUserData……这是我认为的最佳方法。 :)

暂无
暂无

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

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