WorkManager是用于维护延迟或后台执行任务的库。在特定条件下,WorkManager可以在应用程序处于前台时显示通知。使用setForeground()
方法来设置任务优先级,并允许在应用程序处于前台时显示通知。
以下是示例代码:
class MyWorker extends Worker {
private static final String CHANNEL_ID = "MY_CHANNEL_ID";
private static final int NOTIFICATION_ID = 1;
public MyWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
// Do some work here
// ...
// Set the priority of the worker
setForegroundAsync(createForegroundInfo());
// ...
return Result.success();
}
private ForegroundInfo createForegroundInfo() {
// Create a notification channel for the notification
NotificationManager notificationManager =
(NotificationManager) getApplicationContext().
getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
CharSequence name = "My Channel";
String description = "My Channel Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
}
// Create the notification
Notification notification =
new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle("My Notification")
.setContentText("This is my notification.")
.setSmallIcon(R.drawable.ic_notification)
.build();
// Return the foreground info
return new ForegroundInfo(NOTIFICATION_ID, notification);
}
}