Skip to content

Commit

Permalink
Make 3 attempts to start AudioRecord
Browse files Browse the repository at this point in the history
On Android 11, a fake popup must be briefly opened to make the system
think that the shell app is in the foreground so that audio may be
recorded.

Making the shell app foreground may take some time depending on the
device, so make 3 attempts, waiting 100ms before each.

Fixes #3796 <#3796>
  • Loading branch information
rom1v committed Mar 17, 2023
1 parent a387113 commit 02f4ff7
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions server/src/main/java/com/genymobile/scrcpy/AudioCapture.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ private static void startWorkaroundAndroid11() {
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(FakeContext.PACKAGE_NAME, "com.android.shell.HeapDumpActivity"));
ServiceManager.getActivityManager().startActivityAsUserWithFeature(intent);
// Wait for activity to start
SystemClock.sleep(150);
}
}
}
Expand All @@ -84,18 +82,35 @@ private static void stopWorkaroundAndroid11() {
}
}

private void tryStartRecording(int attempts, int delayMs) throws AudioCaptureForegroundException {
while (attempts-- > 0) {
// Wait for activity to start
SystemClock.sleep(delayMs);
try {
recorder = createAudioRecord();
recorder.startRecording();
return; // it worked
} catch (UnsupportedOperationException e) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
if (attempts == 0) {
Ln.e("Failed to start audio capture");
Ln.e("On Android 11, audio capture must be started in the foreground, make sure that the device is unlocked when starting "
+ "scrcpy.");
throw new AudioCaptureForegroundException();
} else {
Ln.d("Failed to start audio capture, retrying...");
}
} else {
throw e;
}
}
}
}

public void start() throws AudioCaptureForegroundException {
startWorkaroundAndroid11();
try {
recorder = createAudioRecord();
recorder.startRecording();
} catch (UnsupportedOperationException e) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
Ln.e("Failed to start audio capture");
Ln.e("On Android 11, it is only possible to capture in foreground, make sure that the device is unlocked when starting scrcpy.");
throw new AudioCaptureForegroundException();
}
throw e;
tryStartRecording(3, 100);
} finally {
stopWorkaroundAndroid11();
}
Expand Down

0 comments on commit 02f4ff7

Please sign in to comment.