Realization of Android Notification Bar Foreground Service
- 2021-11-30 01:30:05
- OfStack
1. A brief introduction to front desk services
Foreground services are those that are thought to be known to the user and are not allowed to be killed by the system when the system runs out of memory. The foreground service must provide a notification to the status bar, which is placed under the running (Ongoing) header--which means that the notification can only be released after the service is terminated or the notification is voluntarily removed from the foreground.
The most common form of expression is music playing service. When the application runs in the background, users can know the current playing content through the notification bar, and carry out related operations such as pause, continue, and cut songs.
2. Why Use Front Desk Services
The priority of Service system running in the background is relatively low, When the system memory is insufficient, the Service running in the background may be recycled. In order to keep the normal operation of the background service and related operations, you can choose to set the Service that needs to be kept running as the foreground service, so that the service can keep working when the APP is in the background for a long time or is closed (the process is not cleaned).
3. Detailed use of front desk services
Create service content, as follows (4 major components do not forget to manifest file registration, or startup will not find the service);
public class ForegroundService extends Service {
private static final String TAG = ForegroundService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
}
}
Create service notification content, such as music playing, Bluetooth device connecting, and so on:
/**
* Create service notifications
*/
private Notification createForegroundNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Only 1 Of the notification channel of id.
String notificationChannelId = "notification_channel_id_01";
// Android8.0 Create a new message channel for the above system
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// User-visible channel name
String channelName = "Foreground Service Notification";
// Importance of channel
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
notificationChannel.setDescription("Channel description");
//LED Lamp
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
// Vibration
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
// Notification icon
builder.setSmallIcon(R.drawable.ic_launcher);
// Notification title
builder.setContentTitle("ContentTitle");
// Notice content
builder.setContentText("ContentText");
// Set the time when the notification is displayed
builder.setWhen(System.currentTimeMillis());
// Set the contents of startup
Intent activityIntent = new Intent(this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// Create a notification and return
return builder.build();
}
When starting the service, create a notification:
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
// Get service notifications
Notification notification = createForegroundNotification();
// Put the service in the startup state ,NOTIFICATION_ID Refers to the created notification ID
startForeground(NOTIFICATION_ID, notification);
}
Remove notification when service is stopped:
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
// Mark service shut down
ForegroundService.serviceIsLive = false;
// Remove notification
stopForeground(true);
super.onDestroy();
}
Determine whether the service is started and obtain the transmission information:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
// Mark service startup
ForegroundService.serviceIsLive = true;
// Data acquisition
String data = intent.getStringExtra("Foreground");
Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
The above is the creation process of the foreground service, and the relevant comments are already very clear. You can see Demo at the end of the article for specific use.
After the service is created, you can start the service next. Don't forget to add foreground service permissions in the manifest file before starting:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Start and stop of service
// Startup service
if (!ForegroundService.serviceIsLive) {
// Android 8.0 Use startForegroundService Start a new service at the front desk
mForegroundService = new Intent(this, ForegroundService.class);
mForegroundService.putExtra("Foreground", "This is a foreground service.");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(mForegroundService);
} else {
startService(mForegroundService);
}
} else {
Toast.makeText(this, " Foreground service is running ...", Toast.LENGTH_SHORT).show();
}
// Stop service
mForegroundService = new Intent(this, ForegroundService.class);
stopService(mForegroundService);
This is the end of the introduction and usage of the foreground service, which has been uploaded to the Github development record. Please click on Star for reference. I will continue to add other useful knowledge and examples to the project.