0

I am trying to start a foreground service in my app. I was informed that there needs to be a notification whenever a service is started for api level 28 and above. Below is the code I used within onstartcommand of my service class

Intent notif=new Intent(this,MyService.class);

PendingIntent  pendingIntent=PendingIntent.getActivity(this,0,notif,0);
  Notification notification=new NotificationCompat.Builder(this)
    .setSmallIcon(R.mipmap.ic_launcher_round)
    .setContentText("w")
    .setContentTitle("jj")
    .setContentIntent(pendingIntent).build(); 
 startForeground(200,notification);

When I do this I receive error

Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null

I have seen posts relating to this such as Bad notification for start Foreground, Invalid channel for service notification: but they all contain a checking for android version 26 and above. What is the best way to handle this error given my min sdk version is 16 and maximum sdk version is 28. This is the first time I am working with services and notifications

This my first time working with services and notifications.

James Z
  • 12,209
  • 10
  • 24
  • 44
Bwalya
  • 118
  • 11
  • 'but they all contain a checking for android version 26 and above" -- correct. You need that logic. On Android 8.0 and higher, you need to use the `NotificationCompat.Builder()` constructor that takes two parameters, where the second parameter is a channel ID, for a notification channel that you create. – CommonsWare Nov 10 '19 at 18:51
  • Ohh, makes sense. The first parameter being? – Bwalya Nov 10 '19 at 19:14
  • The first parameter is as your current code has it: a `Context`. – CommonsWare Nov 10 '19 at 19:44

0 Answers0