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

单击注销时,我将传递要注销的登录用户的会话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!";

其他回答

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

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

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

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

试试看:

当前活动.java

Intent intent = new Intent(currentActivity.this, TargetActivity.class);
intent.putExtra("booktype", "favourate");
startActivity(intent);

目标活动.java

Bundle b = getIntent().getExtras();
String typesofbook = b.getString("booktype");

在android应用程序的活动和其他组件之间传递数据的方法不止一种。一种是使用意图和可分割性,正如很多答案中已经提到的。

另一种优雅的方式是使用Eventbus库。

从排放活动:

EventBus.getDefault().postSticky("--your Object--");

在录制活动中:

EventBus.getDefault().removeStickyEvent("--Object class--")

其他需要考虑的事项:

提供了更多的自由,您可以传递复杂的对象,而无需以任何形式修改它们。不仅限于在活动之间传递数据,一旦设置了库,就可以使用它在应用程序管道中将数据从一个位置传递到另一个位置。例如,将此用于BottomSheetMenu到活动通信。稳定的库。简化了组件之间的通信解耦事件发送器和接收器在UI工件(例如活动、碎片)和后台线程中表现良好避免复杂和容易出错的依赖关系和生命周期问题速度快;专为高性能而优化很小(约60k罐)通过安装量超过1000000000的应用程序在实践中得到了验证具有高级功能,如传递线程、订户优先级等。

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

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

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类使用序列化在类之间传递数据。