在API级别28及更高版本上,Android引入了一些限制,以防止应用程序滥用startForegroundService()和startForeground()方法。以下是在API级别28上正确使用这两个方法的示例代码:
// 在 onCreate() 方法中调用
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourForegroundService.class));
} else {
startService(new Intent(this, YourForegroundService.class));
}
}
// 在 onStartCommand() 方法中调用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "channelId")
.setContentTitle("Foreground Service")
.setContentText("正在运行")
.setSmallIcon(R.drawable.notification_icon)
.build();
startForeground(1, notification);
} else {
Notification notification = new Notification.Builder(this)
.setContentTitle("Foreground Service")
.setContentText("正在运行")
.setSmallIcon(R.drawable.notification_icon)
.build();
startForeground(1, notification);
}
// 执行你的服务逻辑代码
return START_STICKY;
}
请注意,以上示例代码中的YourForegroundService类是继承自Service类的自定义前台服务。你需要根据自己的需求来编写和实现该类中的逻辑代码。
这样,你就可以在API级别28及更高版本上正确地使用startForegroundService()和startForeground()方法来启动和管理前台服务了。