从服务到活动的Android intent.putExtra()

时间:2013-02-04 22:43:47

标签: android service android-activity

一段时间以来,我正试图将String中的简单Service数据传递给Activity Intent.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);

活动代码:

public void onResume() {

    super.onResume();

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

有什么建议吗?

4 个答案:

答案 0 :(得分:5)

为了详细说明我的评论,getIntent返回原始意图,如下所示 [1] http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) [1]:

服务的意图通过在OnResume之前调用的onNewIntent传递给您的活动。因此,如果您覆盖onNewIntent,您将获得预期的字符串。

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

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

}

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

答案 1 :(得分: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);

答案 2 :(得分: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 

并在此处查看一些信息:

How do I pass data between Activities in Android application?

答案 3 :(得分:0)

而不是打电话

extras.getString();

尝试致电:

intent.getStringExtra("key");

另外,您是否直接 FROM 启动了该活动?或者您是否已经在运行活动而只是想从服务中接收数据?