我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
您可以使用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”)等。
其他回答
您可以通过意图在两个活动之间进行沟通。每当您通过登录活动导航到任何其他活动时,都可以将sessionId设置为intent,并通过getIntent()在其他活动中获取。以下是代码段:
登录活动:
Intent intent = new Intent(YourLoginActivity.this,OtherActivity.class);
intent.putExtra("SESSION_ID",sessionId);
startActivity(intent);
finishAfterTransition();
其他活动:
在onCreate()中或需要它调用的任何位置getIntent().getStringExtra(“SESSION_ID”);此外,确保检查intent是否为空,并且在两个活动中传递的intent密钥应该相同。以下是完整的代码片段:
if(getIntent!=null && getIntent.getStringExtra("SESSION_ID")!=null){
sessionId = getIntent.getStringExtra("SESSION_ID");
}
但是,我建议您使用AppSharedPreferences存储sessionId,并在需要时从中获取。
你只需要在表达你的意图时发送额外的信息。
这样地:
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);
如果使用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")
}
源类:
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");
}
正如埃里希指出的那样,传递意图附加是一个好方法。
然而,Application对象是另一种方式,当跨多个活动处理同一状态时(而不是必须在任何地方获取/放置它),或者处理比原语和字符串更复杂的对象时,它有时更容易。
您可以扩展Application,然后使用getApplication()从任何活动(在同一应用程序中)设置/获取所需的内容。
还要记住,您可能看到的其他方法,如静态,可能会有问题,因为它们可能会导致内存泄漏。应用程序也有助于解决这一问题。