我正在尝试使用以下代码从片段生成本地通知。
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mActivity.getApplicationContext());
notificationManager.notify(1, createNotif("test", "test"));
public Notification createNotif(String msg, String title){
String channelId;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelId = "Sample channel";
NotificationChannel notificationChannel = new NotificationChannel(channelId, "sample", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
Notification.Builder notification = new Notification.Builder(getContext(), channelId)
.setContentTitle(title)
.setContentText(msg)
.setStyle(new Notification.BigTextStyle().bigText(msg))
.setOngoing(true)
.setSmallIcon(R.drawable.<>)
.setCategory(Notification.CATEGORY_SERVICE);
return notification.build();
}
}
但是,当我的应用未运行且片段中运行的服务导致本地通知代码运行时,该应用将崩溃,并显示错误消息“片段<>未附加到上下文”。