Skip to content

Commit

Permalink
Fixed ForegroundServiceStartNotAllowedException
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahmud0808 committed Jan 20, 2024
1 parent 48fda9e commit 5d86600
Showing 1 changed file with 8 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.drdisagree.colorblendr.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
Expand Down Expand Up @@ -31,6 +30,7 @@ public class BackgroundService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "Background Service";
private static BroadcastListener myReceiver;
private NotificationManager notificationManager;

public BackgroundService() {
isRunning = false;
Expand All @@ -47,6 +47,10 @@ public IBinder onBind(Intent intent) {
public void onCreate() {
super.onCreate();

if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}

isRunning = true;
createNotificationChannel();
registerReceivers();
Expand Down Expand Up @@ -78,7 +82,7 @@ private void showNotification() {
PendingIntent.FLAG_IMMUTABLE
);

Notification notification = new NotificationCompat.Builder(
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
this,
NOTIFICATION_CHANNEL_ID
)
Expand All @@ -88,10 +92,9 @@ private void showNotification() {
.setContentText(getString(R.string.background_service_notification_text))
.setContentIntent(pendingIntent)
.setSound(null, AudioManager.STREAM_NOTIFICATION)
.setColor(ColorUtil.getAccentColor(this))
.build();
.setColor(ColorUtil.getAccentColor(this));

startForeground(NOTIFICATION_ID, notification);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}

@SuppressWarnings("deprecation")
Expand Down Expand Up @@ -122,7 +125,6 @@ public void createNotificationChannel() {
NotificationManager.IMPORTANCE_LOW
);
channel.setDescription(getString(R.string.background_service_notification_channel_text));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}

Expand Down

0 comments on commit 5d86600

Please sign in to comment.