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

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

本案的任何替代方案


当前回答

您可以使用intent类在Activities之间发送数据。它基本上是一条发送给操作系统的消息,您可以在其中描述数据流的源和目的地。类似于从A到B活动的数据。

在活动A(源)中:

Intent intent = new Intent(A.this, B.class);
intent.putExtra("KEY","VALUE");
startActivity(intent);

在活动B(目标)->

Intent intent =getIntent();
String data =intent.getString("KEY");

在这里,您将获得密钥“key”的数据

为了更好地使用,为了简单起见,密钥应该存储在类中,这将有助于将键入错误的风险降至最低

这样地:

public class Constants{
public static String KEY="KEY"
}

现在在活动A中:

intent.putExtra(Constants.KEY,"VALUE");

在活动B中:

String data =intent.getString(Constants.KEY);

其他回答

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

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...
/*
 * 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));
    }
}

在当前活动中创建新的意向。

String myData="Your string/data here";
Intent intent = new Intent(this, SecondActivity.class);    
intent.putExtra("your_key",myData);
startActivity(intent);

在SecondActivity.java onCreate()中使用键your_key检索这些值

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String myData = extras.getString("your_key");
    }  
}

您可以使用SharedPreferences。。。

登录中。SharedPreferences中的时间存储会话idSharedPreferences preferences=getSharedPreferences(“会话”,getApplicationContext().MODE_PRIVATE);编辑器编辑器=preferences.edit();editer.putString(“sessionId”,sessionId);editer.commit();注销。共享引用中的时间提取会话idSharedPreferences preferences=getSharedPreferences(“会话”,getApplicationContext().MODE_PRIVATE);String sessionId=首选项.getString(“sessionId”,null);

如果您没有所需的会话id,请删除sharedpreferences:

SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();

这非常有用,因为一次保存值,然后检索任何活动。

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

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。