Intent extras没有更新

时间:2014-02-04 20:09:18

标签: android android-intent browser

我正在尝试从浏览器中获取字符串。我在AndroidManifest.xml中使用了SEND操作

<intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
</intent-filter>

在MainActivity.java中,我有以下代码

@Override
public void onResume() {
    super.onResume();
    Intent receivedIntent=getIntent();
    etSearch.setText(getStringFromIntent(receivedIntent));
}

public String getStringFromIntent(Intent receivedIntent) {
    // get the action
    String receivedAction = receivedIntent.getAction();
    // find out what we are dealing with
    String receivedType = receivedIntent.getType();
    if (receivedAction.equals(Intent.ACTION_SEND)) {
        if (receivedType.startsWith("text/")) {
            // get the received text
            String receivedText = receivedIntent
                    .getStringExtra(Intent.EXTRA_TEXT);
            // check we have a string
            if (receivedText != null) {
                // set the text
                return receivedText.trim();
            }
        }
    }
    return "";
}

我第一次尝试分享一切正常 enter image description here

当我尝试再次尝试时,文本不会更新 enter image description here

我认为这是因为onCreate()。所以我将代码移到onResume()中。什么都没发生。

根据此solution,我添加了receivedIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    this.setIntent(intent);
}

没效果。

为了更新意图,我应该怎么做?

1 个答案:

答案 0 :(得分:5)

在创建PendingIntent时使用FLAG_UPDATE_CURRENT来更新新Intent的额外内容。

Intent extras not removed/replaced

PendingIntent.FLAG_ONE_SHOT

private void send(Intent intentShowApp) {
    PendingIntent showAppPendingIntent = PendingIntent.getActivity(context, 0, intentShowApp, PendingIntent.FLAG_ONE_SHOT);
    try {
        showAppPendingIntent.send();
    } catch (CanceledException e) {
        e.printStackTrace();
    }
}