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

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

本案的任何替代方案


当前回答

来自活动

int n= 10;
Intent in = new Intent(From_Activity.this,To_Activity.class);
Bundle b1 = new Bundle();
b1.putInt("integerNumber",n);
in.putExtras(b1);
startActivity(in);

目标活动

Bundle b2 = getIntent().getExtras();
int m = 0;
if(b2 != null){
 m = b2.getInt("integerNumber");
}

其他回答

第一种方式:在当前“活动”中,当您创建一个意图打开新屏幕的对象时:

String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);    
intent.putExtra("key", value);
startActivity(intent);

然后在onCreate方法的nextActivity中,检索从上一个活动传递的值:

if (getIntent().getExtras() != null) {
      String value = getIntent().getStringExtra("key");
      //The key argument must always match that used send and retrieve value from one activity to another.
  }

第二种方法:您可以创建一个bundle对象并将值放入bundle中,然后将bundle对象放入当前活动的意图中-

String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);  
Bundle bundle = new Bundle();
bundle.putInt("key", value);  
intent.putExtra("bundle_key", bundle);
startActivity(intent);

然后在onCreate方法的nextActivity中,检索从上一个活动传递的值:

if (getIntent().getExtras() != null) {
      Bundle bundle = getIntent().getStringExtra("bundle_key");    
      String value = bundle.getString("key");
      //The key argument must always match that used send and retrieve value from one activity to another.
  }

您还可以使用bean类使用序列化在类之间传递数据。

源类:

Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)

目标类(NewActivity类):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

    Intent intent = getIntent();

    String fName = intent.getStringExtra("firstName");
    String lName = intent.getStringExtra("lastName");
}

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

这样地:

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);

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

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

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

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

正如埃里希指出的那样,传递意图附加是一个好方法。

然而,Application对象是另一种方式,当跨多个活动处理同一状态时(而不是必须在任何地方获取/放置它),或者处理比原语和字符串更复杂的对象时,它有时更容易。

您可以扩展Application,然后使用getApplication()从任何活动(在同一应用程序中)设置/获取所需的内容。

还要记住,您可能看到的其他方法,如静态,可能会有问题,因为它们可能会导致内存泄漏。应用程序也有助于解决这一问题。