Foreground services in Android are an important way to perform tasks that should be noticeable to users, such as playing music or tracking fitness activities. They run in the foreground, requiring a notification and ensuring that the service doesn't get stopped by the system when resources are constrained.
In this article, we will explore how to integrate foreground services with other Android components like Activities, Broadcast Receivers, and other Services.
To start a foreground service from an Activity, you need to create an Intent and call startForegroundService()
method.
Intent serviceIntent = new Intent(this, MyForegroundService.class);
ContextCompat.startForegroundService(this, serviceIntent);
A BroadcastReceiver can also start a foreground service, which is useful for starting a service based on an event or system state.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyForegroundService.class);
ContextCompat.startForegroundService(context, serviceIntent);
}
}
You can communicate between an Activity and a foreground service using LocalBroadcastManager
.
// In your service
Intent intent = new Intent("MyData");
intent.putExtra("data", myData);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
// In your activity
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("MyData"));
When the work is done, you should stop the foreground service cleanly.
stopForeground(true);
stopSelf();
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?