Search code examples
androidnotificationsandroid-notifications

Android send out generic notification instead of custom one for foreground service


I'm trying to create a custom notification with an action for my foreground service but for some reason android keeps sending out a generic "{appname} is running in the background | tap for more information or to stop the app" notification.

What I'm doing inside my service class (onStartCommand):

Create the notification channel:

private void createNotificationChannel() {
    NotificationChannel serviceChannel = new NotificationChannel(
            CHANNEL_ID,
            "Foreground Service Channel",
            NotificationManager.IMPORTANCE_DEFAULT
    );
    NotificationManager manager = (NotificationManager) getSystemService(NotificationManager.class);
    manager.createNotificationChannel(serviceChannel);
}

Create an intent (for the contentIntent) and set flags:

 Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            notificationIntent.setAction(Constants.ACTION_MAIN_ACTIVITY);

Create the pending intent for said intent:

 PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

Create the action intent and its pending intent:

 Intent stopIntent = new Intent(this, WebSocketService.class);
 stopIntent.setAction(Constants.ACTION_STOP_SERVICE);

 PendingIntent stopPendingIntent = PendingIntent.getService(this,
                    0, stopIntent,
                    PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

Create the notification itself:

 Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle("Foreground Service")
                    .setTicker("TestTicker")
                    .setContentText("TestText")
                    .setPriority(Notification.PRIORITY_MAX)
                    .setWhen(0)
                    .setOngoing(true)
                    .setContentIntent(pendingIntent)
                    .addAction(android.R.drawable.ic_delete, "Stop", stopPendingIntent);

 Notification not = notification.build();

Start the service:

startForeground(1, not);

I've tested this on multiple devices running different versions of Android (10, 11 and 12) but they all show the same result. Is there anyhthing I'm overlooking? Am I setting the flags wrong on the intents?

Thanks!


Solution

  • Try adding small icon value to the notification builder.

    Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.icon)