从服务(Service)向活动(Activity)发送Android intent.putExtra()

3

最近我一直在尝试使用Intent.putExtra()将简单的字符串数据从Service传递到Activity,但是一直没有成功。无论如何,Intent.getStringExtra()总是NULL。

SERVICE代码:

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

活动代码:

public void onResume() {

    super.onResume();

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

有什么建议吗?

你需要实现onNewIntent方法,通过onNewIntent方法,你的服务中的intent会被发送到你的活动中。 - Hoan Nguyen
只需调用 getIntent().getStringExtra(String) 即可。您没有将 bundle 放入 intent 中。 - user1521536
4个回答

6
为了解释我上面的评论,getIntent返回原始意图,如文档中所述, [1]http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) [1]:
通过onNewIntent将服务的意图传递给您的活动,在onResume之前调用。因此,如果你重写onNewIntent,你就可以得到预期的字符串。
@Override
protected void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);

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

}

那么你的onResume代码将会起作用。


嗯,听起来很有前途。现在会尝试。 - Majstor
好的!!太棒了..谢谢你。我不知道为什么我之前没有想到过,因为我现在已经用了几次onNewIntent..现在也无所谓了。非常感谢你。 - Majstor
当我需要从当前活动返回到一个处于暂停状态的活动时,以下内容对我也有效。 - Waqleh

0

我没有看到你在服务代码中添加 String 的地方,但是你可以运行以下代码来发送字符串。

Intent intent=new Intent(getBaseContext(),MainActivity.class);
Bundle b = new Bundle();
b.putString(Consts.INTERNET_ERROR, "Your String Here");
intent.putExtras(b);
intent.setAction(Consts.INTERNET_ERROR);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

在 Activity 代码中使用您的解决方案时,我得到了一个“NULL”值。刚刚测试过... - Majstor

0

首先:尝试将您的代码从onResume移动到onStart:

public void onStart() {

    super.onStart();

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

如果还不起作用,请尝试以下方法:
第一步骤:
Intent myIntent = new Intent(firstActivity.this, secondActivity.class);
myIntent.putExtra("mystring",strValue)' <=your String
startActivity(myIntent);

第二个活动:
 String str = getIntent.getExtras().getString("mystring");<=get string 

并在此处查看一些信息:

我如何在Android应用程序的活动之间传递数据?


当有人对一个用户进行负投票时,请写下动机,谢谢! - Augusto Picciani
这不是我的问题 :) 我是从服务发送数据到活动,而不是从一个活动到另一个活动。 - Majstor

0

与其调用

extras.getString();

尝试调用:

intent.getStringExtra("key");

此外,您是否直接从服务启动活动?还是您已经在活动上运行,只是想从服务接收数据?


我只是想从服务中获取数据。谢谢你的努力。 - Majstor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接