Skip to content

Commit cf351c9

Browse files
committed
Add try catch for entering foreground in SdlService for TCP connections
1 parent 53ad1fc commit cf351c9

1 file changed

Lines changed: 18 additions & 11 deletions

File tree

  • android/hello_sdl_android/src/main/java/com/sdl/hellosdlandroid

android/hello_sdl_android/src/main/java/com/sdl/hellosdlandroid/SdlService.java

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,18 +104,25 @@ public void onCreate() {
104104
@SuppressLint("NewApi")
105105
public void enterForeground() {
106106
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
107-
NotificationChannel channel = new NotificationChannel(APP_ID, "SdlService", NotificationManager.IMPORTANCE_DEFAULT);
108-
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
109-
if (notificationManager != null) {
110-
notificationManager.createNotificationChannel(channel);
111-
Notification.Builder builder = new Notification.Builder(this, channel.getId())
112-
.setContentTitle("Connected through SDL")
113-
.setSmallIcon(R.drawable.ic_sdl);
114-
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
115-
builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
107+
try {
108+
NotificationChannel channel = new NotificationChannel(APP_ID, "SdlService", NotificationManager.IMPORTANCE_DEFAULT);
109+
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
110+
if (notificationManager != null) {
111+
notificationManager.createNotificationChannel(channel);
112+
Notification.Builder builder = new Notification.Builder(this, channel.getId())
113+
.setContentTitle("Connected through SDL")
114+
.setSmallIcon(R.drawable.ic_sdl);
115+
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
116+
builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
117+
}
118+
Notification serviceNotification = builder.build();
119+
startForeground(FOREGROUND_SERVICE_ID, serviceNotification);
116120
}
117-
Notification serviceNotification = builder.build();
118-
startForeground(FOREGROUND_SERVICE_ID, serviceNotification);
121+
} catch (Exception e) {
122+
// This should only catch for TCP connections on Android 14+ due to needing
123+
// permissions for ForegroundServiceType ConnectedDevice that don't make sense for
124+
// a TCP connection
125+
DebugTool.logError(TAG, "Unable to start service in foreground", e);
119126
}
120127
}
121128
}

0 commit comments

Comments
 (0)