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

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

本案的任何替代方案


当前回答

Intent intent = new Intent(YourCurrentActivity.this, YourActivityName.class);
intent.putExtra("NAme","John");
intent.putExtra("Id",1);
startActivity(intent);

您可以在其他活动中检索它。两种方式:

int id = getIntent.getIntExtra("id", /* defaltvalue */ 2);

第二种方法是:

Intent i = getIntent();
String name = i.getStringExtra("name");

其他回答

/*
 * If you are from transferring data from one class that doesn't
 * extend Activity, then you need to do something like this.
 */ 

public class abc {
    Context context;

    public abc(Context context) {
        this.context = context;
    }

    public void something() {
        context.startactivity(new Intent(context, anyone.class).putextra("key", value));
    }
}

Destination活动的定义如下:

public class DestinationActivity extends AppCompatActivity{

    public static Model model;
    public static void open(final Context ctx, Model model){
          DestinationActivity.model = model;
          ctx.startActivity(new Intent(ctx, DestinationActivity.class))
    }

    public void onCreate(/*Parameters*/){
           //Use model here
           model.getSomething();
    }
}

在第一个活动中,按如下方式开始第二个活动:

DestinationActivity.open(this,model);
 Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity : 

 String userId= getIntent().getStringExtra("("USER_ID");

另一种方法是使用存储数据的公共静态字段,即:

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...

要访问所有活动中的会话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");