我正在创建一个与 SOAP Web 服务交互以从数据库获取数据的应用程序。当用户成功登录时,它会通过网络服务生成一个令牌。稍后在其他活动中调用 Web 服务方法时将需要此令牌。我的问题是,如何在需要时将该令牌传递给下一个活动并维护它直到用户注销。
MainActivity.java
SharedPreferences 首选项=getApplicationContext().getSharedPreferences("YourSessionName", MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("名称",AIMSvalue);
editor.commit();
其他活动.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()方法在您登录时存储令牌。并在您注销或令牌过期时删除该令牌。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)