Skip to content

Commit 3fd2499

Browse files
authored
Merge pull request #1823 from smartdevicelink/bugfix/issue_1815_ForegroundServiceStartNotAllowedException
Android 12 Catch ForegroundServiceStartNotAllowedException
2 parents ccf0af9 + 4f8e483 commit 3fd2499

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlBroadcastReceiver.java

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434

3535
import android.app.ActivityManager;
3636
import android.app.ActivityManager.RunningServiceInfo;
37+
import android.app.ForegroundServiceStartNotAllowedException;
38+
import android.app.ServiceStartNotAllowedException;
3739
import android.bluetooth.BluetoothAdapter;
3840
import android.bluetooth.BluetoothDevice;
3941
import android.bluetooth.BluetoothProfile;
@@ -282,8 +284,8 @@ private static void startRouterService(Context context, ComponentName componentN
282284
restart.putExtra(LOCAL_ROUTER_SERVICE_DID_START_OWN, true);
283285
context.sendBroadcast(restart);
284286

285-
} catch (SecurityException e) {
286-
DebugTool.logError(TAG, "Security exception, process is bad");
287+
} catch (SecurityException | IllegalStateException e) {
288+
handleStartServiceException(e);
287289
}
288290
}
289291

@@ -478,9 +480,8 @@ protected static void pingRouterService(Context context, String packageName, Str
478480
} else {
479481
context.startService(intent);
480482
}
481-
} catch (SecurityException e) {
482-
DebugTool.logError(TAG, "Security exception, process is bad");
483-
// This service could not be started
483+
} catch (SecurityException | IllegalStateException e) {
484+
handleStartServiceException(e);
484485
}
485486
}
486487

@@ -599,6 +600,22 @@ private static boolean isBluetoothConnected() {
599600
return false;
600601
}
601602

603+
private static void handleStartServiceException(Exception e) {
604+
if (e instanceof SecurityException) {
605+
DebugTool.logError(TAG, "Security exception, process is bad");
606+
return;
607+
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
608+
if (e instanceof ForegroundServiceStartNotAllowedException) {
609+
DebugTool.logError(TAG, "Not allowed to start service in foreground");
610+
return;
611+
} else if (e instanceof ServiceStartNotAllowedException) {
612+
DebugTool.logError(TAG, "Not allowed to start service in current state");
613+
return;
614+
}
615+
}
616+
DebugTool.logError(TAG, "Unable to start service for unknown reason");
617+
}
618+
602619

603620
private static SdlDeviceListener getSdlDeviceListener(Context context, BluetoothDevice bluetoothDevice) {
604621

0 commit comments

Comments
 (0)