从传入的Intent中删除额外内容

And*_*rew 59 android android-intent

我有一个搜索屏幕,可以通过点击另一个屏幕的"名称"字段启动.

如果用户遵循此工作流程,我会在Intent的Extras中添加一个名为"search"的额外内容.此额外使用填充"name"字段的文本作为其值.创建搜索屏幕时,该额外用作搜索参数,并为用户自动启动搜索.

但是,由于Android会在屏幕旋转时销毁并重新创建活动,因此旋转手机会再次导致自动搜索.因此,我想在执行初始搜索时从Activity的Intent中删除"搜索"额外内容.

我试过这样做:

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey("search")) {
            mFilter.setText(extras.getString("search"));
            launchSearchThread(true);
            extras.remove("search");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.如果我再次旋转屏幕,活动的意图的额外内容中仍然存在额外的"搜索".

有任何想法吗?

And*_*rew 134

我有它的工作.

似乎getExtras()创建了 Intent的附加组件的副本.

如果我使用以下行,这可以正常工作:

getIntent().removeExtra("search");
Run Code Online (Sandbox Code Playgroud)

源代码 getExtras()

/**
 * Retrieves a map of extended data from the intent.
 *
 * @return the map of all extras previously added with putExtra(),
 * or null if none have been added.
 */
public Bundle getExtras() {
    return (mExtras != null)
            ? new Bundle(mExtras)
            : null;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你检查此行后面的值,那么你会发现值没有从Intent中删除.我以同样的方式尝试,然后尝试看到意图被删除与否.getIntent()removeExtra( "搜索").String searchText = extras.getString("search"); searchText的值相同.我试过extras.remove("搜索"); 之后该值为null. (3认同)
  • 这里也有很好的答案:http://stackoverflow.com/questions/20447643/permanently-modify-intent-that-started-an-activity如果有人想修改活动意图 (2认同)
  • @NewGuy 删除了这个答案上的复选标记,因为它不再有效。 (2认同)

w3b*_*ark 9

虽然@Andrew 的回答可能提供了一种删除特定 Intent extra 的方法,但有时需要清除所有 Intent Extras,在这种情况下,您将需要使用

Intent.replaceExtras(new Bundle())
Run Code Online (Sandbox Code Playgroud)

的源代码replaceExtras

/**
 * Completely replace the extras in the Intent with the given Bundle of
 * extras.
 *
 * @param extras The new set of extras in the Intent, or null to erase
 * all extras.
 */
public @NonNull Intent replaceExtras(@NonNull Bundle extras) {
    mExtras = extras != null ? new Bundle(extras) : null;
    return this;
}
Run Code Online (Sandbox Code Playgroud)


Gre*_*ryK 8

可以使用在破坏和重新创建期间持久的额外标志来解决该问题.这是缩小的代码:

boolean mProcessed;

@Override
protected void onCreate(Bundle state) {
    super.onCreate(state);
    mProcessed = (null != state) && state.getBoolean("state-processed");
    processIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    mProcessed = false;
    processIntent(intent);
}

@Override
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    state.putBoolean("state-processed", mProcessed);
}

protected void processIntent(Intent intent) {
    // do your processing
    mProcessed = true;
}
Run Code Online (Sandbox Code Playgroud)

  • 一个缺点是,这是一次性答案。如果新的意图伴随着新的附加功能,这个解决方案也不会考虑它 (2认同)