我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。

单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?

本案的任何替代方案


当前回答

在当前活动中,创建一个新的意向:

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("key",value);
startActivity(i);

然后在新的“活动”中,检索这些值:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}

使用此技术将变量从一个Activity传递到另一个Activity。

其他回答

试试看:

当前活动.java

Intent intent = new Intent(currentActivity.this, TargetActivity.class);
intent.putExtra("booktype", "favourate");
startActivity(intent);

目标活动.java

Bundle b = getIntent().getExtras();
String typesofbook = b.getString("booktype");

在当前活动中,创建一个新的意向:

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("key",value);
startActivity(i);

然后在新的“活动”中,检索这些值:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
}

使用此技术将变量从一个Activity传递到另一个Activity。

对于在所有活动中使用会话id,可以执行以下步骤。

1-在应用程序的APPLICATION文件中定义一个静态变量会话(将保存会话id的值)。

2—现在用类引用调用会话变量,在那里获取会话id值,并将其分配给静态变量。

3-现在,您可以通过调用

数据对象应扩展Parcelable或Serializable类。

Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);

要访问所有活动中的会话id,必须将会话id存储在SharedPreference中。

请参见下面我用于管理会话的类,您也可以使用该类。

import android.content.Context;
import android.content.SharedPreferences;

public class SessionManager {

    public static String KEY_SESSIONID = "session_id";

    public static String PREF_NAME = "AppPref";

    SharedPreferences sharedPreference;
    SharedPreferences.Editor editor;
    Context mContext;

    public SessionManager(Context context) {
        this.mContext = context;

        sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreference.edit();
    }


    public String getSessionId() {
        return sharedPreference.getString(KEY_SESSIONID, "");
    }

    public void setSessionID(String id) {
        editor.putString(KEY_SESSIONID, id);
        editor.commit();
        editor.apply();
    }   
}

//Now you can access your session using below methods in every activities.

    SessionManager sm = new SessionManager(MainActivity.this);
sm.getSessionId();



//below line us used to set session id on after success response on login page.

    sm.setSessionID("test");