Android intent.putExtra() 从服务到 Activity

标签 android service android-activity

一段时间以来,我一直在尝试使用 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/

相关文章:

android - Android 平板电脑上的 HTML/CSS/JS/Java IDE 可能吗?

android - 单击图像时如何在 Activity 上以 fragment 形式显示图像?

android - 如何按下前台服务通知?

Grails 服务不是事务性的?

Android Activity 由于堆 fragment 导致服务崩溃

android - 如何在 Galaxy Tab 中使用 Intent 捕获视频?

javascript - 如何创建新文件

javascript - Angular.js 中的 Utils 类

java - 启动 Android Activity 会给出 IllegalStateException/InvocationTargetException

Android,finish()关闭应用程序而不是 Activity