首页 > 解决方案 > 为什么 Activity getIntent().getExtras() 有时会返回 null?

问题描述

我有一个活动,在极少数情况下,它getIntent().getExtras()会返回null

public class NewNoteChecklistLauncherFragmentActivity extends AppCompatActivity {
    private static final String NEW_NOTE_CHECKLIST_LAUNCHER_FRAGMENT = "NEW_NOTE_CHECKLIST_LAUNCHER_FRAGMENT";

    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.mAppWidgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

        FragmentManager fm = getSupportFragmentManager();
        NewNoteChecklistLauncherFragment newNoteChecklistLauncherFragment = (NewNoteChecklistLauncherFragment) fm.findFragmentByTag(NEW_NOTE_CHECKLIST_LAUNCHER_FRAGMENT);

        if (newNoteChecklistLauncherFragment == null) {
            Bundle bundle = this.getIntent().getExtras();
            if (bundle == null) {
                // WHY?
                throw new java.lang.RuntimeException();
            }

我不确定这是怎么发生的。因为,每次,我都会发起Activitywith call toputExtra

Intent i = new Intent(context, NewNoteChecklistLauncherFragmentActivity.class);
Note note = new Note();
i.putExtra(NewNoteChecklistLauncherFragment.INTENT_EXTRA_NOTE, note);

同时,它还充当“分享”动作的意图过滤器。

<activity android:name="com.yocto.wenote.note.NewNoteChecklistLauncherFragmentActivity"
    android:theme="@style/Theme.Transparent"
    android:windowSoftInputMode="stateAlwaysHidden" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>

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

    <intent-filter>
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

我无法产生这样的问题。但是,有一段时间,我可以看到这样的事情发生在生产中。

任何想法,在什么情况下,getIntent().getExtras()会返回null上述情况?

标签: android

解决方案


这可能是一个错误的ACTION_SEND实现,未能附加任何附加功能。这可能是一些自动化脚本——或脚本小子——手动调用你的活动,没有任何额外的东西。

由于活动是导出的,我推荐一些“防御性编程”。不要假设存在临时演员Bundle。相反,在这种情况下,尽可能“优雅地降级”。


推荐阅读