java.lang.RuntimeException:无法启动接收器

时间:2017-05-20 13:24:56

标签: android android-fragments

我是Android的初学者。我想在特定日期显示通知。当我尝试运行方法showNotification()时,我收到以下错误:

  

java.lang.RuntimeException:无法启动接收器   com.example.azernax.dforget.ScheduleNotification:   java.lang.NullPointerException:尝试调用虚方法   ' java.lang.String android.content.Context.getPackageName()'在null   对象参考

我试图修复此错误但没有成功。

ScheduleNotification:

public class ScheduleNotification extends WakefulBroadcastReceiver {

private AlarmManager alarmManager;

@Override
public void onReceive(Context context, Intent intent) {
    ScheduleNotification.completeWakefulIntent(intent);

    //create notification to show !!!
    Toast.makeText(context, "TEST schedule!!!! ", Toast.LENGTH_LONG).show();
    Notification_center notification = new Notification_center();
    notification.showNotification();  //######################### CRASH !!!!
}

Notification_center:

public class Notification_center extends AppCompatActivity {

public void showNotification()
{
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.icon);
    builder.setContentTitle("dF Notification!");
    builder.setContentText("description"); //--description event--

    Intent intent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NM.notify(0,builder.build());
}

1 个答案:

答案 0 :(得分:1)

Notification_center notification = new Notification_center();

从不自己创建活动的实例,因为它永远无法正常运行。

将代码从showNotification()移至onReceive()。您可以使用Context作为onReceive()的{​​{1}}替代this以及getSystemService()的来电。

此外,您在此处不需要WakefulBroadcastReceiver。这适用于您需要将工作委托给其他人的情况(例如,IntentService)。如果所有工作都在onReceive()结束时完成,则您无需管理单独的WakeLock,这是WakefulBroadcastReceiver的用途。