在 Android 中,可以使用一个服务类为多个通知提供服务。以下是实现的步骤:
public class NotificationService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
public void createNotification(String title, String message, int notificationId) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_DEFAULT); notificationManager.notify(notificationId, builder.build()); }
NotificationService notificationService = new NotificationService(); notificationService.createNotification("Title", "Message", 1); notificationService.createNotification("Title", "Message", 2); notificationService.createNotification("Title", "Message", 3);
注意:服务类必须在 AndroidManifest.xml 文件中声明。在使用服务类时,需要使用 startService() 方法启动服务。
startService(new Intent(this, NotificationService.class));