Skip to content

Display and control your Android device

Call Looper.prepareMainLooper() to avoid exception

olbbe282100d0b79
diff --git a/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java b/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java
index 8357b061..52f6f26b 100644
--- a/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java
+++ b/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java
@@ -7,6 +7,7 @@ import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.IBinder;
+import android.os.Looper;
import android.view.Surface;
import java.io.FileDescriptor;
@@ -54,6 +55,16 @@ public class ScreenEncoder implements Device.RotationListener {
}
public void streamScreen(Device device, FileDescriptor fd) throws IOException {
+ // Some devices internally create a Handler when creating an input Surface, causing an exception:
+ // "Can't create handler inside thread that has not called Looper.prepare()"
+ // <https://github.com/Genymobile/scrcpy/issues/240>
+ //
+ // Use Looper.prepareMainLooper() instead of Looper.prepare() to avoid a NullPointerException:
+ // "Attempt to read from field 'android.os.MessageQueue android.os.Looper.mQueue'
+ // on a null object reference"
+ // <https://github.com/Genymobile/scrcpy/issues/921>
+ Looper.prepareMainLooper();
+
MediaFormat format = createFormat(bitRate, frameRate, iFrameInterval);
device.setRotationListener(this);
boolean alive;