要解决在前台应用程序中启动服务时出现的“Android 9 (!) IllegalStateException”异常,您可以使用以下方法:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android 9及更高版本
startForegroundService(new Intent(this, MyService.class));
} else {
// Android 8及更低版本
startService(new Intent(this, MyService.class));
}
// 在服务的onCreate方法中添加前台服务通知
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "my_service_channel";
NotificationChannel channel = new NotificationChannel(channelId, "My Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle("My Service")
.setContentText("Running in foreground")
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(1, notification);
} else {
// 低于Android 8的版本,不需要前台服务通知
}
}
请确保在代码中替换MyService为您的服务类的名称,以及适当设置通知标题、内容和图标。
通过执行上述步骤,您应该能够解决“Android 9 (!) IllegalStateException”异常并在前台应用程序中启动服务。
上一篇:Android 8中的后台服务(无JobScheduler)- Xamarin
下一篇:Android 9 (API 28)应用在启动时出现activity崩溃(setContentView)的问题。