广播接收器传值至Alarm Activity时Bundle返回null,设默认值仍报错
问题分析与解决方法
嘿,我一眼就发现你代码里的核心问题啦!空指针异常的根源其实是你把额外数据放错了Intent对象,再加上几个小细节没注意到,一起来修复:
1. BroadcastReceiver里的关键错误
你在onReceive方法里新建了normalReminderIntent,但却把Bundle数据加到了方法参数的intent里,而不是你要启动的normalReminderIntent!这就导致启动Activity时,Intent根本没携带任何数据,Activity里调用intent.getExtras()自然返回null,触发空指针。
另外,从BroadcastReceiver启动Activity必须添加FLAG_ACTIVITY_NEW_TASK标记,否则会抛出Activity启动异常。
修正后的BroadcastReceiver代码:
@Override public void onReceive(Context context, Intent intent) { Intent normalReminderIntent = new Intent(context.getApplicationContext(), ReminderAlarmActivity.class); // Bundle information and add to the INTENT YOU'RE GOING TO START Bundle extras = new Bundle(); extras.putString("Title", title); extras.putString("Description", description); normalReminderIntent.putExtras(extras); // 把数据放到要启动的Intent里! // 必须添加这个标记,否则从BroadcastReceiver启动Activity会失败 normalReminderIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Start the reminder activity context.getApplicationContext().startActivity(normalReminderIntent); }
2. Activity里的优化与空指针规避
你现在的写法是先调用getExtras(),如果这个方法返回null,再调用getString()就会触发空指针。其实Android的Intent提供了更安全的getStringExtra(String key, String defaultValue)方法,直接跳过Bundle的获取,即使没有对应key或者没有Bundle,也会返回默认值。
修正后的Activity代码:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { setTheme(R.style.AppTheme_Dialog); super.onCreate(savedInstanceState); setContentView(R.layout.alarm_activity_reminder); // Get the bundled info for title and description Intent intent = getIntent(); // 用getStringExtra直接获取,避免空指针 String title = intent.getStringExtra("Title", ""); String description = intent.getStringExtra("Description", ""); }
关于Stub方法的说明
你看到的getString方法定义里的throw new RuntimeException("Stub!")是Android SDK的占位代码,实际运行时系统会替换为真实的实现逻辑,完全不用在意这个,它不会影响你的代码运行。
内容的提问来源于stack exchange,提问作者Nicholas Muir
相关产品推荐
相关产品推荐

