I've got foreground service targeting android 8. There is service notification like "voip service runnig" when some app activity is visible.
The problem is that when app goes background, android show additional system notification "App is running in the background".
How to avoid this? Users do not like to see two ongoing notifications for one app.
screen with service noty only,
screen with service & system noty
code:
public class MyService extends Service {
String TAG = "MyService";
public MyService() {
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate: ");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Notification notification = new NotificationCompat.Builder(this, TestApplication.PRIMARY_NOTIF_CHANNEL)
.setSmallIcon(android.R.drawable.ic_menu_call)
.setContentText("ServiceText")
.setContentTitle("ServiceTitle")
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.build();
startForeground(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
}
}
public class TestApplication extends Application {
public static final String PRIMARY_NOTIF_CHANNEL = "default";
public static final int PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel chan1 = new NotificationChannel(
PRIMARY_NOTIF_CHANNEL,
"default",
NotificationManager.IMPORTANCE_HIGH);
chan1.setLightColor(Color.TRANSPARENT);
chan1.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(chan1);
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContextCompat.startForegroundService(this, new Intent(this, MyService.class));
}
}