Я хочу создать приложение для Android с push-уведомлениями, которые также показывают, закрыто ли приложение.Мне удалось сделать это с JobSceduler, и он отлично работает, если приложение находится только в фоновом режиме.Но если я закрою приложение (проведите пальцем), оно не будет работать.Событие по-прежнему периодически запускается, как видно из журнала ошибок, но приложение не может создать уведомление:
Ошибка:
java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.NotificationManagerCompat.notify(int, android.app.Notification)' on a null object reference
at android.app.job.JobService$JobHandler.handleMessage(JobService.java:147)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6623)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.NotificationManagerCompat.notify(int, android.app.Notification)' on a null object reference
at xxx.MainActivity.buildNotification(MainActivity.java:484)
Код для MainActivity.java, где происходит ошибка:
Intent notificationIntent = new Intent(MyApplication.getContext(), MainActivity.class);
notificationIntent.putExtra("sendSomeData", sendSomeData); // not necessary at the moment
PendingIntent contentIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification1Summary = new NotificationCompat.Builder(MyApplication.getContext(), CHANNEL_1_ID)
.setSmallIcon(R.drawable.noti_icon)
.setContentTitle("Truth or Date")
.setContentText("You have new messages")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(new long[]{0, 400, 200, 400}) // sleep, vibrate, in milliseconds
.setAutoCancel(true) // delete after user clicks on it
//.setOngoing(true) // keep it alive even if clicked on notification
.setGroup(groupid) // new group key.. all comments will be grouped in one shout
.setGroupSummary(true)
//.setContentIntent(contentIntent) // when user clicks on notification
.build();
notification1 = new NotificationCompat.Builder(MyApplication.getContext(), CHANNEL_1_ID)
.setSmallIcon(R.drawable.noti_icon)
.setContentTitle(title)
.setContentText(text)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(text))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(new long[]{0, 400, 200, 400}) // sleep, vibrate, in milliseconds
.setAutoCancel(true) // delete after user clicks on it
//.setOngoing(true) // keep it alive even if clicked on notification
.setGroup(groupid) // new group key.. all comments will be grouped in one shout
// .setGroupSummary(true)
.setContentIntent(contentIntent) // when user clicks on notification
.build();
notificationManager.notify(Integer.parseInt(groupid), notification1Summary);
notificationManager.notify(commentid, notification1);
Код из MyApplication.java (откуда я получаю контекст):
private static MyApplication instance;
private static Context mContext;
public static MyApplication getInstance() {
return instance;
}
public static Context getContext() {
return mContext;
}
Моя теория
Моя теория заключается в том, что проблема заключается в контексте Уведомления.Я думаю, что приложение не может получить контекст от MyApplication.getContext (), если приложение полностью закрыто.
...new NotificationCompat.Builder(MyApplication.getContext()...
Я пытался заменить его getApplicationContext () и этим, но он также дает другие ошибки.Есть ли способ узнать об этой проблеме?Есть ли у вас какие-либо другие предложения о том, что вызывает проблему?(Я также пытался сделать это с AlarmManager и BroadcastReciever, но ошибка та же)
Спасибо!