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

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

本案的任何替代方案


当前回答

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

其他回答

最简单的方法是将会话id传递给用于启动活动的Intent中的注销活动:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

访问下一个活动的意图:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

Intents的文档有更多信息(请参阅标题为“附加”的部分)。

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

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

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

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

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

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

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

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

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

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