0

I am trying to generate a local notification from a fragment, using the following code.

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();
                } 
    }

But when my app in not running and a service running in my fragment causes the local notification code to run, the app crashes giving the error that "Fragment <> not attached to a context".

Tulika
  • 625
  • 1
  • 8
  • 23

0 Answers0