【问题标题】:NullPointerException on BroadCastReceiver class;BroadCastReceiver 类上的 NullPointerException;
【发布时间】:2017-04-24 17:09:51
【问题描述】:

我的应用程序包含一个本地人列表,每个本地人都有一个日期。当我单击本地时,我会使用本地信息打开一个新活动,并根据此日期创建警报。警报应在本地提供的日期前 2 天唤醒。我就是这样做的:

当我进入本地Activity时:

private void scheduleAlarm(Date notificationDate) {
    Intent intent = new Intent(getApplicationContext(), Receiver.class).putExtra("myString", myString);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarm.set(AlarmManager.RTC, notificationDate.getTime(), pendingIntent);
}

接收者类别:

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String myString = intent.getStringExtra("myString");
        if (myString.matches("myString") Toast.makeText(context, "Working", Toast.LENGTH_SHORT).show();
    }
}

在清单中注册:

<receiver android:name=".Receiver" android:enabled="true" >
    <intent-filter android:priority="999" >
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

这通常可以正常工作,但是当我重新启动手机时,当我进入主屏幕时,我的应用程序就会崩溃。

我在我的应用程序上实现了结构崩溃分析,如果我检查崩溃,我的 Receiver.class 上会出现 NullPointerException: pattern == null。

我敢打赌,当我重新启动手机时,我失去了额外的意图,并且这条线得到了 NullPointerException:

String myString = intent.getStringExtra("myString");

有人知道吗?我应该如何处理这个崩溃?

【问题讨论】:

  • 如果我检查 myString 是否为 null 或匹配“”,否则只继续,我不会崩溃,所以我确实遇到了这个崩溃,因为当我重新启动手机时额外内容为 null .

标签: java android android-intent nullpointerexception crash


【解决方案1】:

作为一般规则,请执行"myString".matches(myString),您不必执行两次检查。

意图没有额外功能的原因是因为您没有收到警报事件,而是BOOT_COMPLETED 事件,它没有任何额外功能。启动完成后,您将需要重新安排警报、附加功能和所有内容,因为 AlarmManager 不会在重新启动后持续存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多