1@Override
2public void onCreate(){
3 super.onCreate();
4 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
5 startMyOwnForeground();
6 else
7 startForeground(1, new Notification());
8}
9
10private void startMyOwnForeground(){
11 String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
12 String channelName = "My Background Service";
13 NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
14 chan.setLightColor(Color.BLUE);
15 chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
16 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
17 assert manager != null;
18 manager.createNotificationChannel(chan);
19
20 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
21 Notification notification = notificationBuilder.setOngoing(true)
22 .setSmallIcon(R.drawable.icon_1)
23 .setContentTitle("App is running in background")
24 .setPriority(NotificationManager.IMPORTANCE_MIN)
25 .setCategory(Notification.CATEGORY_SERVICE)
26 .build();
27 startForeground(2, notification);
28}