如何在Android中的本地或会话存储中存储令牌?
问题描述:
我正在创建一个与SOAP Web服务进行交互以从数据库获取数据的应用程序。当用户成功登录时,它会通过网络服务生成一个令牌。稍后在其他活动中需要此标记来调用Web服务方法。我的问题是,如何在需要时将该令牌传递给下一个活动,并在用户注销之前将其保留。如何在Android中的本地或会话存储中存储令牌?
MainActivity.java
SharedPreferences偏好= getApplicationContext()getSharedPreferences( “YourSessionName”,MODE_PRIVATE)。 SharedPreferences.Editor editor = preferences.edit(); editor.putString(“name”,AIMSvalue);
editor.commit();
OtherActivity.java
SharedPreferences preferences=getSharedPreferences("YourSessionName", MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
token=preferences.getString("name","");
editor.commit();
答
public class CommonUtilities {
private static SharedPreferences.Editor editor;
private static SharedPreferences sharedPreferences;
private static Context mContext;
/**
* Create SharedPreference and SharedPreferecne Editor for Context
*
* @param context
*/
private static void createSharedPreferenceEditor(Context context) {
try {
if (context != null) {
mContext = context;
} else {
mContext = ApplicationStore.getContext();
}
sharedPreferences = context.getSharedPreferences(IConstants.SAMPLE_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Put String in SharedPreference Editor
*
* @param context
* @param key
* @param value
*/
public static void putPrefString(Context context, String key, String value) {
try {
createSharedPreferenceEditor(context);
editor.putString(key, value);
editor.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
使用此putString()方法来存储一个令牌,当你登录,并删除标记,当您退出或令牌过期。
+0
我已经做到了这一点,但没有工作。在调用登录后调用第二种Web服务方法时,它始终将其视为新请求,即从登录屏幕生成的令牌不能正确传递到另一个屏幕。@ Kush Patel –
我认为[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences.html)是正确的地方 –
没有它的不工作。 –
使用SharedPreferences时遇到了什么问题? –