我喜欢这样
第一路
Intent intent = new Intent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);
第二种方式
Intent intent = getIntent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);
两者都能给出相同的结果。我想知道这两者之间的实际差异
最佳答案
在Activity
的上下文中,getIntent()
将返回最初发送到Intent
的Activity
。您提供的示例可能会起作用,但是如果要将getIntent()
传递给另一个Intent
或将其发送回去,则应避免使用Activity
。
例如:
如果我通过以下活动开始活动:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", "test");
startActivity(intent);
然后在我的MainActivity类中:
Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".
因此,现在考虑您是否具有SecondActivity,而我正在使用getInent()从MainActivity启动它;
Intent intent = getIntent();
intent.setClassName("com.example.pkg", "com.example.pkg.SecondActivity"");
intent.setComponent(new ComponentName("com.example.pkg", "com.example.pkg.SecondActivity"));
intent.putExtra("isLoggedIn",true);
startActivity(intent);
然后,在我的SecondActivity中,我可以访问key和isLoggedIn。
Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".
boolean testIsLoggedIn = intent.getBooleanExtra("isLoggedIn",true);
因此,通常不建议使用getIntent启动更多活动。