How does Foreground services work internally in Android SDK?

Foreground services in Android are designed to perform operations that are noticeable to the user, such as playing music, handling file uploads, or tracking location. These services are given higher priority by the Android system, which ensures that they are less likely to be killed when the device is low on resources.

When an app starts a foreground service, it must show a notification to inform the user that the service is running. This notification is displayed in the system tray, ensuring that users are always aware of foreground activities that could affect device performance or battery life.

To implement a foreground service, developers use the startForeground() method. This method is typically called within the onStartCommand() method of a service, where the notification is created and shown.

        public class MyForegroundService extends Service {
            @Override
            public void onCreate() {
                super.onCreate();
                // Create the notification
                Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("My Service")
                        .setContentText("Service is running in foreground")
                        .setSmallIcon(R.drawable.ic_notification)
                        .build();

                // Start the service in the foreground
                startForeground(1, notification);
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
                // Logic for the service
                return START_STICKY;
            }

            @Override
            public void onDestroy() {
                super.onDestroy();
                // Clean up service
            }

            @Nullable
            @Override
            public IBinder onBind(Intent intent) {
                return null; // Not a bound service
            }
        }
        

foreground services android service lifecycle Android SDK service notification