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

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


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部