> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zwc456baby/ScrcpyForAndroid/llms.txt
> Use this file to discover all available pages before exploring further.

# Scrcpy Service

> Core Android service for managing screen mirroring connections and event handling

## Overview

The `Scrcpy` class is the main Android service that manages the client-side screen mirroring functionality. It handles socket connections to the scrcpy server, manages video and audio decoders, and processes touch and key events.

**Package:** `org.client.scrcpy`

**Extends:** `android.app.Service`

## Starting the Service

### start()

Initializes and starts the scrcpy service with screen mirroring.

```java theme={null}
public void start(Surface surface, String serverAdr, int screenHeight, 
                  int screenWidth, int delay)
```

<ParamField path="surface" type="Surface" required>
  The Android Surface to render video output
</ParamField>

<ParamField path="serverAdr" type="String" required>
  Server address in format "host:port" (e.g., "127.0.0.1:7008")
</ParamField>

<ParamField path="screenHeight" type="int" required>
  Height of the display surface in pixels
</ParamField>

<ParamField path="screenWidth" type="int" required>
  Width of the display surface in pixels
</ParamField>

<ParamField path="delay" type="int" required>
  Network delay tolerance in milliseconds for frame dropping
</ParamField>

**Example:**

```java theme={null}
Scrcpy scrcpy = new Scrcpy();
Surface surface = surfaceView.getHolder().getSurface();
scrcpy.start(surface, "127.0.0.1:7008", 1920, 1080, 100);
```

## Touch Event Handling

### touchevent()

Processes touch events and sends them to the remote device with coordinate transformation.

```java theme={null}
public boolean touchevent(MotionEvent touch_event, boolean landscape, 
                          int displayW, int displayH)
```

<ParamField path="touch_event" type="MotionEvent" required>
  The Android MotionEvent to process
</ParamField>

<ParamField path="landscape" type="boolean" required>
  Whether the remote device is in landscape orientation
</ParamField>

<ParamField path="displayW" type="int" required>
  Current display width in pixels
</ParamField>

<ParamField path="displayH" type="int" required>
  Current display height in pixels
</ParamField>

<ResponseField name="return" type="boolean">
  Returns `true` if the event was processed successfully
</ResponseField>

**Supported Actions:**

* `ACTION_DOWN` - First finger touch
* `ACTION_UP` - Last finger lift
* `ACTION_MOVE` - Touch movement (all fingers)
* `ACTION_POINTER_DOWN` - Additional finger touch
* `ACTION_POINTER_UP` - Additional finger lift

**Example:**

```java theme={null}
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (scrcpy != null) {
        return scrcpy.touchevent(event, true, 1080, 1920);
    }
    return super.onTouchEvent(event);
}
```

**Multi-touch Support:**

The method handles multi-touch by iterating through all pointer indices for `ACTION_MOVE` events:

```java theme={null}
// From source (Scrcpy.java:163-170)
for (int i = 0; i < touch_event.getPointerCount(); i++) {
    int currentPointerId = touch_event.getPointerId(i);
    int x = (int) touch_event.getX(i);
    int y = (int) touch_event.getY(i);
    sendTouchEvent(touch_event.getAction(), touch_event.getButtonState(), 
                   (int) (x * realW / displayW), (int) (y * realH / displayH), 
                   currentPointerId);
}
```

## Key Event Handling

### sendKeyevent()

Sends a key event to the remote device.

```java theme={null}
public void sendKeyevent(int keycode)
```

<ParamField path="keycode" type="int" required>
  Android KeyEvent keycode (e.g., `KeyEvent.KEYCODE_BACK`, `KeyEvent.KEYCODE_HOME`)
</ParamField>

**Example:**

```java theme={null}
// Send back button
scrcpy.sendKeyevent(KeyEvent.KEYCODE_BACK);

// Send home button
scrcpy.sendKeyevent(KeyEvent.KEYCODE_HOME);

// Send volume up
scrcpy.sendKeyevent(KeyEvent.KEYCODE_VOLUME_UP);
```

## Lifecycle Methods

### pause()

Pauses video and audio decoding without disconnecting.

```java theme={null}
public void pause()
```

**Example:**

```java theme={null}
@Override
protected void onPause() {
    super.onPause();
    if (scrcpy != null) {
        scrcpy.pause();
    }
}
```

### resume()

Resumes video and audio decoding after pause.

```java theme={null}
public void resume()
```

**Example:**

```java theme={null}
@Override
protected void onResume() {
    super.onResume();
    if (scrcpy != null) {
        scrcpy.resume();
    }
}
```

### StopService()

Stops all decoders and terminates the service.

```java theme={null}
public void StopService()
```

**Example:**

```java theme={null}
@Override
protected void onDestroy() {
    if (scrcpy != null) {
        scrcpy.StopService();
    }
    super.onDestroy();
}
```

## ServiceCallbacks Interface

Implement this interface to receive service events.

```java theme={null}
public interface ServiceCallbacks {
    void loadNewRotation();
    void errorDisconnect();
}
```

### setServiceCallbacks()

Registers a callback listener.

```java theme={null}
public void setServiceCallbacks(ServiceCallbacks callbacks)
```

<ParamField path="callbacks" type="ServiceCallbacks" required>
  Implementation of the ServiceCallbacks interface
</ParamField>

**Callback Methods:**

<ResponseField name="loadNewRotation" type="void">
  Called when the remote device rotation changes and a new surface is needed
</ResponseField>

<ResponseField name="errorDisconnect" type="void">
  Called when the connection is lost or an error occurs
</ResponseField>

**Example:**

```java theme={null}
scrcpy.setServiceCallbacks(new Scrcpy.ServiceCallbacks() {
    @Override
    public void loadNewRotation() {
        // Handle rotation change
        runOnUiThread(() -> {
            // Recreate surface with new dimensions
            updateSurfaceOrientation();
        });
    }
    
    @Override
    public void errorDisconnect() {
        // Handle disconnection
        runOnUiThread(() -> {
            Toast.makeText(context, "Connection lost", Toast.LENGTH_SHORT).show();
            finish();
        });
    }
});
```

## Connection Information

### get\_remote\_device\_resolution()

Returns the remote device's native resolution.

```java theme={null}
public int[] get_remote_device_resolution()
```

<ResponseField name="return" type="int[]">
  Array of two integers \[width, height] representing the device resolution
</ResponseField>

**Example:**

```java theme={null}
int[] resolution = scrcpy.get_remote_device_resolution();
int width = resolution[0];
int height = resolution[1];
Log.d("Scrcpy", "Remote device: " + width + "x" + height);
```

### check\_socket\_connection()

Checks if the socket connection is established.

```java theme={null}
public boolean check_socket_connection()
```

<ResponseField name="return" type="boolean">
  Returns `true` if connected, `false` otherwise
</ResponseField>

**Example:**

```java theme={null}
if (!scrcpy.check_socket_connection()) {
    Toast.makeText(this, "Not connected to device", Toast.LENGTH_SHORT).show();
}
```

## Constants

<ResponseField name="LOCAL_IP" type="String">
  Default local IP address: `"127.0.0.1"`
</ResponseField>

<ResponseField name="LOCAL_FORWART_PORT" type="int">
  Default forwarding port: `7008`
</ResponseField>

<ResponseField name="DEFAULT_ADB_PORT" type="int">
  Default ADB port: `5555`
</ResponseField>

## Event Data Format

Touch and key events are serialized as byte arrays before transmission:

**Touch Event Format (20 bytes):**

```
Bytes 0-3:   action (int)
Bytes 4-7:   buttonState (int)
Bytes 8-11:  x coordinate (int)
Bytes 12-15: y coordinate (int)
Bytes 16-19: pointerId (int)
```

**Key Event Format (4 bytes):**

```
Bytes 0-3: keycode (int)
```

## See Also

* [Video Decoder](/api/video-decoder) - Video stream decoding
* [Audio Decoder](/api/audio-decoder) - Audio stream decoding
* [Event Controller](/api/event-controller) - Server-side event handling
