Junior — Middle
What is the purpose of the Foreground service in Android and how is it used?
sobes.tech AI
Answer from AI
Foreground Service in Android is used for performing tasks that should continue even when the user is not directly interacting with the app, such as playing music, tracking location, or downloading files. The main difference of a Foreground Service is the mandatory display of a notification in the status bar, informing the user that the service is active.
Usage:
- It is started using the
startForegroundService()method. - Inside the service,
startForeground(notificationId, notification)is called to show the notification. - This prevents the system from killing the service when resources are low.
Example of starting a Foreground Service:
public class MyForegroundService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Service is running")
.setContentText("Performing an important task")
.setSmallIcon(R.drawable.ic_service_icon)
.build();
startForeground(1, notification);
// Service logic
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}