3

一段时间以来,我试图将简单的String数据从 theService传递到ActivitywithIntent.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

4 回答 4

6

为了详细说明我上面的评论,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 将起作用。

于 2013-02-05T03:15:29.833 回答
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);
于 2013-02-04T22:50:18.133 回答
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 应用程序的活动之间传递数据?

于 2013-02-05T01:53:51.290 回答
0

而不是打电话

extras.getString();

尝试调用:

intent.getStringExtra("key");

另外,您是否直接服务开始活动?或者您是否已经在活动上运行并且只是想从服务接收数据?

于 2013-02-05T02:05:52.907 回答