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

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

本案的任何替代方案


当前回答

我在类中使用静态字段,并获取/设置它们:

喜欢:

public class Info
{
    public static int ID      = 0;
    public static String NAME = "TEST";
}

要获取值,请在“活动”中使用:

Info.ID
Info.NAME

要设置值:

Info.ID = 5;
Info.NAME = "USER!";

其他回答

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

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

你只需要在表达你的意图时发送额外的信息。

这样地:

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);

现在,在SecondActivity的OnCreate方法中,您可以像这样获取额外内容。

如果您发送的值过长:

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));

如果发送的值是字符串:

String value = getIntent().getStringExtra("Variable name which you sent as an extra");

如果发送的值是布尔值:

Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);

我们可以通过两种方式将值传递给另一个Activity(已经发布了相同类型的答案,但我在这里发布了通过意图尝试的redcing代码)

1.通过意图

  Activity1:
      startActivity(new Intent(getApplicationContext(),Activity2.class).putExtra("title","values"));

InActivity 2:

String recString= getIntent().getStringExtra("title");

2.通过SharedPreference

  Activity1:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
 // 0 - for private mode
Editor editor = pref.edit();
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes

Activty2:
   SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

pref.getString("key_name", null); // getting String

如果使用kotlin:

在MainActivity1中:

var intent=Intent(this,MainActivity2::class.java)
intent.putExtra("EXTRA_SESSION_ID",sessionId)
startActivity(intent)

在MainActivity2中:

if (intent.hasExtra("EXTRA_SESSION_ID")){
    var name:String=intent.extras.getString("sessionId")
}

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

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

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

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