gpt4 book ai didi

java - Context.startForegroundService() 然后没有调用 Service.Foreground

转载 作者:行者123 更新时间:2023-12-01 23:08:30 26 4
gpt4 key购买 nike

如果设备操作系统是 Android 9(Pie),我已调用 Context.startForgroundService() 但有时它会抛出错误,例如“Context.startForgroundService() 没有调用 Service.Forground”,我有还授予前台服务 android.permission.FOREGROUND_SERVICE 权限,但问题仍未解决。

if (!isMyServiceRunning(Service.class)){
startService();
}

private void startService() {
System.out.println("Start Service");
Thread t = new Thread("StartService") {
public void run() {
Intent serviceIntent = new Intent("com.demo.demo.start_service");
serviceIntent.setPackage("com.demo.demo");
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getApplicationContext().startForegroundService(serviceIntent);

} else {
getApplicationContext().startService(serviceIntent);
}
}catch (Exception e){
e.printStackTrace();
}
}

};
t.start();
}

最佳答案

前台服务的问题是它应该在5秒内启动,否则你会发现这个错误。现在我向你分享了这个方法,我在我的服务类ONCREATE方法上使用它。我希望您觉得这很有用。

void CheckOSversion()
{
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("")
.build();

startForeground(002, notification);
}

}

关于java - Context.startForegroundService() 然后没有调用 Service.Foreground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com