Skip to content

Commit 6cd8d1d

Browse files
authored
Merge pull request NordicSemiconductor#431 from NordicSemiconductor/bugfix/foreground-service
Foreground service behavior fixed
2 parents 95c5c39 + a17d794 commit 6cd8d1d

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

lib/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,11 @@ void restartService(@NonNull final Intent intent, final boolean scanForBootloade
831831
// Reset the DFU attempt counter
832832
intent.putExtra(DfuBaseService.EXTRA_DFU_ATTEMPT, 0);
833833

834-
mService.startService(intent);
834+
final boolean foregroundService = intent.getBooleanExtra(DfuBaseService.EXTRA_FOREGROUND_SERVICE, true);
835+
if (foregroundService && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
836+
mService.startForegroundService(intent);
837+
else
838+
mService.startService(intent);
835839
}
836840

837841
protected String parse(@Nullable final byte[] data) {

lib/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,7 +1356,11 @@ protected void onHandleIntent(@Nullable final Intent intent) {
13561356
final Intent newIntent = new Intent();
13571357
newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE);
13581358
newIntent.putExtra(EXTRA_RECONNECTION_ATTEMPT, attempt + 1);
1359-
startService(newIntent);
1359+
1360+
if (foregroundService && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
1361+
startForegroundService(newIntent);
1362+
else
1363+
startService(newIntent);
13601364
return;
13611365
}
13621366
terminateConnection(gatt, mError);
@@ -1415,7 +1419,11 @@ protected void onHandleIntent(@Nullable final Intent intent) {
14151419
final Intent newIntent = new Intent();
14161420
newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE);
14171421
newIntent.putExtra(EXTRA_DFU_ATTEMPT, attempt + 1);
1418-
startService(newIntent);
1422+
1423+
if (foregroundService && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
1424+
startForegroundService(newIntent);
1425+
else
1426+
startService(newIntent);
14191427
return;
14201428
}
14211429
report(ERROR_DEVICE_DISCONNECTED);
@@ -1914,7 +1922,12 @@ private void startForeground() {
19141922
// Any additional configuration?
19151923
updateForegroundNotification(builder);
19161924

1917-
startForeground(NOTIFICATION_ID, builder.build());
1925+
try {
1926+
startForeground(NOTIFICATION_ID, builder.build());
1927+
} catch (final SecurityException e) {
1928+
loge("Service cannot be started in foreground", e);
1929+
logi("Starting DFU service in background instead");
1930+
}
19181931
}
19191932

19201933
/**

0 commit comments

Comments
 (0)