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

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

本案的任何替代方案


当前回答

如果使用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")
}

其他回答

活动之间的数据传递主要通过意向对象进行。

首先,必须使用Bundle类将数据附加到intent对象。然后使用startActivity()或startActivityForResult()方法调用活动。

您可以从博客文章“将数据传递给活动”中找到更多信息。

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

喜欢:

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

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

Info.ID
Info.NAME

要设置值:

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

我们可以通过两种方式将值传递给另一个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

您可以使用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();

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

您可以使用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);