Android 从传入的意图中删除额外内容

Android 从传入的意图中删除额外内容,android,android-intent,Android,Android Intent,我有一个搜索屏幕,可以通过点击另一个屏幕的“名称”字段启动 如果用户遵循此工作流,我会在意图的附加部分中添加一个称为“搜索”的附加部分。此额外值使用填充“name”字段的文本作为其值。创建搜索屏幕时,该额外值将用作搜索参数,并自动为用户启动搜索 然而,由于Android在屏幕旋转时会破坏并重新创建活动,因此旋转手机会再次导致自动搜索。因此,在执行初始搜索时,我希望从活动的意图中删除额外的“搜索” 我试过这样做: Bundle extras = getIntent().getExtras(

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

如果用户遵循此工作流,我会在意图的附加部分中添加一个称为“搜索”的附加部分。此额外值使用填充“name”字段的文本作为其值。创建搜索屏幕时,该额外值将用作搜索参数,并自动为用户启动搜索

然而,由于Android在屏幕旋转时会破坏并重新创建活动,因此旋转手机会再次导致自动搜索。因此,在执行初始搜索时,我希望从活动的意图中删除额外的“搜索”

我试过这样做:

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey("search")) {
            mFilter.setText(extras.getString("search"));
            launchSearchThread(true);
            extras.remove("search");
        }
    }
然而,这是行不通的。如果我再次旋转屏幕,“搜索”额外内容仍然存在于活动的意图的额外内容中

有什么想法吗?

我有办法

似乎getExtras()创建了意图的extras的副本

如果我使用下面的行,它可以正常工作:

getIntent().removeExtra("search");
getExtras()的源代码


这个问题可以通过使用额外的标志来解决,该标志在销毁和重新创建期间是持久的。以下是缩小的代码:

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;
}

虽然@Andrew的回答可能提供了一种删除特定意图额外项的方法,但有时有必要清除所有意图额外项,在这种情况下,您需要使用

Intent.replaceExtras(new Bundle())
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;
}

如果您在这一行之后检查该值,则会发现该值未从意图中删除。我以同样的方式试过,然后试着看意图是否被移除。getIntent().removeExtra(“搜索”);String searchText=extras.getString(“搜索”);searchText的值相同。我尝试了附加功能。删除(“搜索”);该值之后为null。@AnilChahal可能是onNewIntent()同时被调用,并且您已经覆盖了实际的“intent”值。好的答案是:如果有人想要修改活动intent@Andrew如何删除任何意图,而不仅仅是由特定字符串值定义的意图?@NewGuy删除了此答案上的复选标记,因为它不再有效。一个缺点是,这是一次性答案。如果new intent附带了新的额外功能,那么这个解决方案将不会在传入
intent.replaceExtras(null)
时考虑它。
/**
 * 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;
}