如何将令牌存储在Android的本地或会话存储中? [英] How to store the token in Local or session storage in android?

查看:825
本文介绍了如何将令牌存储在Android的本地或会话存储中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个与SOAP Web服务交互以从数据库获取数据的应用程序.用户成功登录后,它将通过Web服务生成令牌.稍后在其他活动中将需要此令牌来调用Web服务方法.我的问题是,如何在需要时将该令牌传递给下一个活动,并维护该令牌直到用户注销.

I'm creating an app that interacts with SOAP web-services to get data from the database. When the user successfully logins it generates a token via web-services. This token will be needed later on in other activities to call web-service methods. My question is, how can I pass on that token to the next activity when its needed and maintain it until the user logs out.

MainActivity.java

MainActivity.java

SharedPreferences preferences = getApplicationContext().getSharedPreferences("YourSessionName",MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("name",AIMSvalue);

SharedPreferences preferences=getApplicationContext().getSharedPreferences("YourSessionName", MODE_PRIVATE); SharedPreferences.Editor editor=preferences.edit(); editor.putString("name",AIMSvalue);

                    editor.commit();

OtherActivity.java

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()方法在登录时存储令牌.在注销或令牌过期时删除该令牌.

Use this putString() method to store a token when you logged in. And remove that token when you logged out or token expires.

这篇关于如何将令牌存储在Android的本地或会话存储中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆