在 activity 中,如果 activity 暂停然后用意图调用,getIntent() returns 旧的
In an activity, if the activity is paused and then invoked with an intent, getIntent() returns the old one
我有一个 activity,它根据启动 activity 的意图显示一些信息。应用程序图标启动此 activity,没有任何额外信息,并且 activity 正确显示。应用程序小部件也启动此 activity,但有一些额外的信息并得到正确处理。在这种情况下,应用程序无法按预期运行:
用户使用主屏幕快捷方式输入 activity。
用户使用主页键将应用程序发送到后台。
用户使用小部件快捷方式进入应用
在这种情况下,onResume() 中的意图是旧意图,而不是来自小部件的意图。
我该如何解决这个问题?
这正是 onNewIntent() 存在的原因:它被称为:
when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
An activity will always be paused before receiving a new intent, so you can count on onResume()
being called after this method.
Note that getIntent()
still returns the original Intent. You can use setIntent(Intent)
to update it to this new Intent.
因此添加代码如:
@Override
protected void onNewIntent (Intent intent) {
setIntent(intent);
}
And/or 将您的代码从 onResume()
移动到诸如 handleIntent()
的方法中,并从您的 onCreate()
和 onNewIntent()
调用它。
我有一个 activity,它根据启动 activity 的意图显示一些信息。应用程序图标启动此 activity,没有任何额外信息,并且 activity 正确显示。应用程序小部件也启动此 activity,但有一些额外的信息并得到正确处理。在这种情况下,应用程序无法按预期运行:
用户使用主屏幕快捷方式输入 activity。 用户使用主页键将应用程序发送到后台。 用户使用小部件快捷方式进入应用
在这种情况下,onResume() 中的意图是旧意图,而不是来自小部件的意图。 我该如何解决这个问题?
这正是 onNewIntent() 存在的原因:它被称为:
when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
An activity will always be paused before receiving a new intent, so you can count on
onResume()
being called after this method.Note that
getIntent()
still returns the original Intent. You can usesetIntent(Intent)
to update it to this new Intent.
因此添加代码如:
@Override
protected void onNewIntent (Intent intent) {
setIntent(intent);
}
And/or 将您的代码从 onResume()
移动到诸如 handleIntent()
的方法中,并从您的 onCreate()
和 onNewIntent()
调用它。