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

Maj*_*tor 3 service android android-activity

一段时间以来,我正试图将简单的一个String数据传递ServiceActivitywith,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);
Run Code Online (Sandbox Code Playgroud)

活动代码:

public void onResume() {

    super.onResume();

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

有什么建议?

Hoa*_*yen 6

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

服务的意图通过onNewIntent传递给您的活动,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);

}
Run Code Online (Sandbox Code Playgroud)

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