Report specific error for INJECT_EVENT permission

Some devices require a specific option to be enabled in Developer
Options to avoid a permission issue when injecting input events.

When this error occurs, hide the stack trace and print a human-readable
message explaining how to fix the issue.

PR #6080 <https://github.com/Genymobile/scrcpy/pull/6080>
This commit is contained in:
Romain Vimont 2025-05-09 18:22:40 +02:00
commit 8cd63cb63e
2 changed files with 20 additions and 1 deletions

View file

@ -58,7 +58,7 @@ Make sure you [enabled USB debugging][enable-adb] on your device(s).
On some devices (especially Xiaomi), you might get the following error:
```
java.lang.SecurityException: Injecting input events requires the caller (or the source of the instrumentation, if any) to have the INJECT_EVENTS permission.
Injecting input events requires the caller (or the source of the instrumentation, if any) to have the INJECT_EVENTS permission.
```
In that case, you need to enable [an additional option][control] `USB debugging

View file

@ -6,6 +6,7 @@ import android.annotation.SuppressLint;
import android.view.InputEvent;
import android.view.MotionEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@SuppressLint("PrivateApi,DiscouragedPrivateApi")
@ -17,6 +18,7 @@ public final class InputManager {
private final Object manager;
private Method injectInputEventMethod;
private long lastPermissionLogDate;
private static Method setDisplayIdMethod;
private static Method setActionButtonMethod;
@ -57,6 +59,23 @@ public final class InputManager {
Method method = getInjectInputEventMethod();
return (boolean) method.invoke(manager, inputEvent, mode);
} catch (ReflectiveOperationException e) {
if (e instanceof InvocationTargetException) {
Throwable cause = e.getCause();
if (cause instanceof SecurityException) {
String message = e.getCause().getMessage();
if (message != null && message.contains("INJECT_EVENTS permission")) {
// Do not flood the console, limit to one permission error log every 3 seconds
long now = System.currentTimeMillis();
if (lastPermissionLogDate <= now - 3000) {
Ln.e(message);
Ln.e("Make sure you have enabled \"USB debugging (Security Settings)\" and then rebooted your device.");
lastPermissionLogDate = now;
}
// Do not print the stack trace
return false;
}
}
}
Ln.e("Could not invoke method", e);
return false;
}