200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java中intent什么意思_java-如何判断Android是否存在Intent Extras?

java中intent什么意思_java-如何判断Android是否存在Intent Extras?

时间:2022-07-08 11:01:54

相关推荐

java中intent什么意思_java-如何判断Android是否存在Intent Extras?

正如其他人所说,Intent和getBoolean("isNewItem", false)都可能返回null。 因此,您不想将调用链接在一起,否则可能最终会调用null.getBoolean("isNewItem");,这将抛出NullPointerException,并导致您的应用程序崩溃。

这就是我要完成的方法。 我认为它以最好的方式格式化,并且可能被正在阅读您的代码的其他人轻易理解。

// You can be pretty confident that the intent will not be null here.

Intent intent = getIntent();

// Get the extras (if there are any)

Bundle extras = intent.getExtras();

if (extras != null) {

if (extras.containsKey("isNewItem")) {

boolean isNew = extras.getBoolean("isNewItem", false);

// TODO: Do something with the value of isNew.

}

}

您实际上不需要呼叫Intent,因为如果不存在多余的内容,则getBoolean("isNewItem", false)将返回false。 您可以将以上内容浓缩为以下形式:

Bundle extras = getIntent().getExtras();

if (extras != null) {

boolean isNew = extras.getBoolean("isNewItem", false);

if (isNew) {

// Do something

} else {

// Do something else

}

}

您还可以使用Intent方法直接访问您的附加功能。 这可能是最干净的方法:

boolean isNew = getIntent().getBooleanExtra("isNewItem", false);

实际上,这里的任何方法都是可以接受的。 选择一个对您有意义的方式,然后按照这种方式进行。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。