From e829012ee6dbfb641ba723feb1bb24f9a9486ed8 Mon Sep 17 00:00:00 2001
From: armv9 <48624112+arm64v8a@users.noreply.github.com>
Date: Tue, 8 Apr 2025 15:01:22 +0900
Subject: [PATCH] Use systemExempt foreground service type for VPNService
---
app/src/main/AndroidManifest.xml | 21 +++++++--------
.../sagernet/bg/ServiceNotification.kt | 27 ++++++++++++-------
2 files changed, 27 insertions(+), 21 deletions(-)
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index c0ed87d..9e7a740 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -13,7 +13,7 @@
-
+
@@ -258,36 +258,33 @@
-
-
+ android:foregroundServiceType="systemExempted"
+ android:process=":bg"
+ tools:ignore="ForegroundServicePermission" />
+ android:process=":bg"
+ tools:ignore="ForegroundServicePermission">
-
diff --git a/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt b/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt
index 3efd3f4..0ac84ac 100644
--- a/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt
+++ b/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt
@@ -6,9 +6,10 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
-import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
+import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
import android.os.Build
import android.text.format.Formatter
+import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.nekohasekai.sagernet.Action
@@ -185,14 +186,22 @@ class ServiceNotification(
private suspend fun show() =
useBuilder {
- if (Build.VERSION.SDK_INT >= 34) {
- (service as Service).startForeground(
- notificationId,
- it.build(),
- FOREGROUND_SERVICE_TYPE_SPECIAL_USE
- )
- } else {
- (service as Service).startForeground(notificationId, it.build())
+ try {
+ if (Build.VERSION.SDK_INT >= 34) {
+ (service as Service).startForeground(
+ notificationId,
+ it.build(),
+ FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
+ )
+ } else {
+ (service as Service).startForeground(notificationId, it.build())
+ }
+ } catch (e: Exception) {
+ Toast.makeText(
+ SagerNet.application,
+ "startForeground: $e",
+ Toast.LENGTH_LONG
+ ).show()
}
}