用于存储用户的登录凭据Android的最好的地方最好的、凭据、地方、用户

2023-09-05 09:47:24 作者:十年戎马心孤单

我创建一个Android应用程序,我不能(?)找到验证在谷歌的App Engine应用程序的用户的任何信息(不使用用户的谷歌帐户)。是它很好的做法存储的用户名和密码的Android设备然后存储使用的谷歌应用程序引擎?

I am creating an android app, and i cannot(?) find any information on authenticating a user of the app on Google App Engine (without using the user's Google Account).Is it good practice to store username and password on the android device and then store the data used by the app on Google App Engine?

推荐答案

考虑的共享preferences 了解这一点,就像...

Consider SharedPreferences for this, like...

public class PrefUtils {
    public static final String PREFS_LOGIN_USERNAME_KEY = "__USERNAME__" ;
    public static final String PREFS_LOGIN_PASSWORD_KEY = "__PASSWORD__" ;

    /**
     * Called to save supplied value in shared preferences against given key.
     * @param context Context of caller activity
     * @param key Key of value to save against
     * @param value Value to save
     */
    public static void saveToPrefs(Context context, String key, String value) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key,value);
        editor.commit();
    }

    /**
     * Called to retrieve required value from shared preferences, identified by given key.
     * Default value will be returned of no value found or error occurred.
     * @param context Context of caller activity
     * @param key Key to find value against
     * @param defaultValue Value to return if no data found against given key
     * @return Return the value found against given key, default if not found or any error occurs
     */
    public static String getFromPrefs(Context context, String key, String defaultValue) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        try {
            return sharedPrefs.getString(key, defaultValue);
        } catch (Exception e) {
             e.printStackTrace();
             return defaultValue;
        }
    }
}

简单地使用这些方法,比如,

Simply use these methods like,

// Saving user credentials on successful login case
PrefUtils.saveToPrefs(YourActivity.this, PREFS_LOGIN_USERNAME_KEY, username);
PrefUtils.saveToPrefs(YourActivity.this, PREFS_LOGIN_PASSWORD_KEY, password);

// To retrieve values back
String loggedInUserName = PrefUtils.getFromPrefs(YourActivity.this, PREFS_LOGIN_USERNAME_KEY);
String loggedInUserPassword = PrefUtils.getFromPrefs(YourActivity.this, PREFS_LOGIN_PASSWORD_KEY);

我现在认为它更清楚...:)

I think its much clearer now...:)