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

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

本案的任何替代方案


当前回答

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

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

其他回答

如果要在活动/片段之间传输位图


活动

在活动之间传递位图

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

在“活动”类中

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

碎片

在片段之间传递位图

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

在SecondFragment内部接收

Bitmap bitmap = getArguments().getParcelable("bitmap");

传输大型位图

如果您正在获取失败的绑定器事务,这意味着您正在通过将大型元素从一个活动转移到另一个活动来超出绑定器事务缓冲区。

因此,在这种情况下,您必须将位图压缩为字节数组,然后在另一个活动中解压缩,如下所示

在第一个活动中

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

在第二次活动中

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

最简单的方法是将会话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的文档有更多信息(请参阅标题为“附加”的部分)。

您可以使用intent对象在活动之间发送数据。假设您有两个活动,即FirstActivity和SecondActivity。

内部第一活动:

使用意图:

i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)

内部第二活动

Bundle bundle= getIntent().getExtras();

现在,您可以使用不同的bundle类方法获取通过Key从FirstActivity传递的值。

例如。bundle.getString(“key”)、bundle.get-Double(“key“)、bundle.getInt(“key”)等。

 Intent intent = new Intent(getBaseContext(), SomeActivity.class);
 intent.putExtra("USER_ID", UserId);
 startActivity(intent);

 On SomeActivity : 

 String userId= getIntent().getStringExtra("("USER_ID");

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