gpt4 book ai didi

Android intent.putExtra() 从服务到 Activity

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:48 25 4
gpt4 key购买 nike

一段时间以来,我一直在尝试使用 Intent 将 Service 中的简单 String 数据传递给 Activity .putExtra() 但没有成功。 Intent.getStringExtra() 始终为 NULL

服务代码:

Intent intent=new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Consts.INTERNET_ERROR, "error");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

Activity 代码:

public void onResume() {

super.onResume();

Intent i = getIntent();
String test = "temp";
Bundle b = i.getExtras();
if (b != null) {
test = b.getString(Consts.INTERNET_ERROR);
}
}

有什么建议吗?

最佳答案

为了详细说明我上面的评论,getIntent 返回原始 Intent ,如记录在[1] http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)[1]:

来自服务的 Intent 通过在 onResume 之前调用的 onNewIntent 传递给您的 Activity 。因此,如果您覆盖 onNewIntent,您将获得预期的字符串。

@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);

// set the string passed from the service to the original intent
setIntent(intent);

}

然后您的 onResume 代码将起作用。

关于Android intent.putExtra() 从服务到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14697133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com