Shizuku can do the two one-time adb steps from the phone, so Android stops asking to share the screen every drive

This commit is contained in:
Seb3thehacker committed 2026-11-24 00:32:32 -08:00
1 parent e62a6503cc
commit 24880edc9b
14 files changed
+296 -1

No files matched your search

+5
View File
@@ -119,6 +119,8 @@ android {
buildFeatures {
buildConfig = true
// IShellService, the part of Gearslip that Shizuku runs with adb's powers.
aidl = true
}
// Lists each language that has a translation in the app's locale config, so Android 13+
@@ -200,6 +202,9 @@ dependencies {
implementation(libs.androidx.webkit)
// The map behind a place list (PlaceListMapTemplate), which the host draws, not the app.
implementation(libs.maplibre.android)
// Shizuku, Apache 2.0. Optional: everything works without it, it only skips setup steps.
implementation(libs.shizuku.api)
implementation(libs.shizuku.provider)
testImplementation(libs.junit)
}
+3
View File
@@ -11,3 +11,6 @@
# Speech-to-text: the native library calls back into these classes by name.
-keep class com.k2fsa.sherpa.onnx.** { *; }
# Shizuku starts the shell service in its own process by class name, with no caller R8 can see.
-keep class app.seb3thehacker.gearslip.shizuku.ShellService { <init>(...); *; }
+11
View File
@@ -128,6 +128,8 @@
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
<!-- Whether Shizuku is installed, so its setup button shows only for those who have it. -->
<package android:name="moe.shizuku.privileged.api" />
</queries>
<!--
@@ -144,6 +146,15 @@
android:manageSpaceActivity="app.seb3thehacker.gearslip.ui.ManageSpaceActivity"
android:theme="@style/Theme.Gearslip">
<!-- How Shizuku hands Gearslip its binder. Only Shizuku, running as the system, can call it. -->
<provider
android:name="rikka.shizuku.ShizukuProvider"
android:authorities="${applicationId}.shizuku"
android:multiprocess="false"
android:enabled="true"
android:exported="true"
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.logshare"
@@ -0,0 +1,10 @@
package app.seb3thehacker.gearslip.shizuku;
// The part of Gearslip that Shizuku runs as the shell user, with the same powers as adb.
interface IShellService {
// Shizuku's own transaction code for ending the service process.
void destroy() = 16777114;
// Runs a shell command and returns its exit code. Only Gearslip's own fixed commands.
int run(String command) = 1;
}
@@ -148,6 +148,7 @@ class GearslipActivity : ComponentActivity(), Projection {
GearslipLog.init(this)
GearslipLog.installCrashHandler()
GearslipLog.i("Gearslip ready")
app.seb3thehacker.gearslip.shizuku.ShizukuSetup.init(this)
app.seb3thehacker.gearslip.wireless.WirelessLink.onConnected = { socket ->
runOnUiThread { startWireless(socket) }
}
@@ -663,6 +663,7 @@ class GearslipRunner(
// A car known to switch Bluetooth music off gets it through Gearslip, whatever the setting.
CarSettings.carConnected(ServiceDiscovery.findBluetoothService(serviceDiscoveryResponse)?.carAddress)
BluetoothAudioCheck.onCarFound()
app.seb3thehacker.gearslip.car.CarEnvironment.appContext?.let { app.seb3thehacker.gearslip.shizuku.ShizukuSetup.recheckOnConnect(it) }
if (CarSettings.pipesNow) {
if (!CarSettings.pipeAudio.value) log.i("this car turns Bluetooth music off, so music goes through Gearslip")
openChannel(media.serviceId)
@@ -0,0 +1,23 @@
package app.seb3thehacker.gearslip.shizuku
import androidx.annotation.Keep
import kotlin.system.exitProcess
/**
* Runs in a process Shizuku starts as the shell user, so a command here has the same powers it
* would have typed over adb. Nothing in this class may touch the rest of Gearslip: it lives in a
* different process, with a different user, and only sees what [run] is handed.
*/
@Keep
class ShellService : IShellService.Stub() {
override fun destroy() {
exitProcess(0)
}
override fun run(command: String): Int {
val process = ProcessBuilder("sh", "-c", command).redirectErrorStream(true).start()
process.inputStream.readBytes()
return process.waitFor()
}
}
@@ -0,0 +1,182 @@
package app.seb3thehacker.gearslip.shizuku
import android.Manifest
import android.app.AppOpsManager
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import app.seb3thehacker.gearslip.BuildConfig
import app.seb3thehacker.gearslip.GearslipLog
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import rikka.shizuku.Shizuku
/**
* Shizuku does Gearslip's one-time adb steps from the phone (issue #125). Both stick once done:
*
* - the PROJECT_MEDIA app-op, so Android stops asking to share the screen every drive
* - WRITE_SECURE_SETTINGS, so notifications stay readable while music is captured
*
* Everything works without Shizuku; this only saves the trip to a computer. Once both are in
* place Shizuku isn't needed again, but each car connection checks, and quietly puts back
* whatever went missing if Shizuku happens to be running.
*/
object ShizukuSetup {
enum class State {
/** Shizuku isn't installed. Nothing about it is shown. */
MISSING,
/** Installed, but its service isn't running. */
STOPPED,
/** Running, and Gearslip hasn't been allowed to use it yet. */
NEEDS_PERMISSION,
/** Running and allowed. */
READY,
}
private const val SHIZUKU_PACKAGE = "moe.shizuku.privileged.api"
private const val REQUEST_CODE = 125
private val main = Handler(Looper.getMainLooper())
private val log = GearslipLog.tagged("shizuku")
private val _state = MutableStateFlow(State.MISSING)
val state: StateFlow<State> = _state
private val _granted = MutableStateFlow(false)
/** True once both one-time steps are in place, by Shizuku or by adb. */
val granted: StateFlow<Boolean> = _granted
private val _working = MutableStateFlow(false)
val working: StateFlow<Boolean> = _working
private var appContext: Context? = null
/** Waiting on the driver's answer to Shizuku's permission dialog. */
private var afterPermission: (() -> Unit)? = null
fun init(context: Context) {
if (appContext != null) return
appContext = context.applicationContext
Shizuku.addBinderReceivedListenerSticky { refresh() }
Shizuku.addBinderDeadListener { refresh() }
Shizuku.addRequestPermissionResultListener { code, result ->
if (code != REQUEST_CODE) return@addRequestPermissionResultListener
refresh()
val next = afterPermission
afterPermission = null
if (result == PackageManager.PERMISSION_GRANTED) next?.invoke()
else log.i("the driver didn't allow Gearslip to use Shizuku")
}
refresh()
}
fun refresh() {
val context = appContext ?: return
_granted.value = hasProjectMedia(context) && hasSecureSettings(context)
_state.value = when {
!installed(context) -> State.MISSING
!runCatching { Shizuku.pingBinder() }.getOrDefault(false) -> State.STOPPED
runCatching { Shizuku.checkSelfPermission() }.getOrDefault(PackageManager.PERMISSION_DENIED) !=
PackageManager.PERMISSION_GRANTED -> State.NEEDS_PERMISSION
else -> State.READY
}
}
/** The button: asks Shizuku for permission if needed, then does both steps. */
fun setUp() {
refresh()
when (_state.value) {
State.READY -> grant()
State.NEEDS_PERMISSION -> {
afterPermission = ::grant
runCatching { Shizuku.requestPermission(REQUEST_CODE) }
.onFailure { log.e("could not ask Shizuku for permission", it) }
}
else -> Unit
}
}
/** A car connected: put back anything missing, without asking, if Shizuku is up and allowed. */
fun recheckOnConnect(context: Context) = main.post {
init(context)
refresh()
if (!_granted.value && _state.value == State.READY) {
log.i("a one-time setup step is missing, and Shizuku is running, so Gearslip is putting it back")
grant()
}
}
private fun grant() {
val context = appContext ?: return
if (_working.value) return
_working.value = true
val pkg = context.packageName
val commands = buildList {
if (!hasProjectMedia(context)) {
add("appops set $pkg PROJECT_MEDIA allow")
add("appops write-settings")
}
if (!hasSecureSettings(context)) add("pm grant $pkg ${Manifest.permission.WRITE_SECURE_SETTINGS}")
}
withShell(
onReady = { shell ->
for (command in commands) {
val code = runCatching { shell.run(command) }.getOrDefault(-1)
log.i("ran \"$command\" through Shizuku: exit $code")
}
},
onDone = {
_working.value = false
refresh()
log.i(if (_granted.value) "one-time setup done through Shizuku" else "Shizuku ran, but the setup still isn't in place")
},
)
}
/** Starts [ShellService] in Shizuku's shell process, runs [onReady] off the main thread, then stops it. */
private fun withShell(onReady: (IShellService) -> Unit, onDone: () -> Unit) {
val context = appContext ?: return onDone()
val args = Shizuku.UserServiceArgs(ComponentName(context, ShellService::class.java))
.daemon(false)
.processNameSuffix("shell")
.debuggable(BuildConfig.DEBUG)
.version(BuildConfig.VERSION_CODE)
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
val conn = this
val shell = binder?.let { IShellService.Stub.asInterface(it) }
Thread {
if (shell != null) onReady(shell) else log.w("Shizuku started the shell service without a binder")
main.post {
runCatching { Shizuku.unbindUserService(args, conn, true) }
onDone()
}
}.start()
}
override fun onServiceDisconnected(name: ComponentName?) = Unit
}
runCatching { Shizuku.bindUserService(args, connection) }.onFailure {
log.e("could not start the shell service through Shizuku", it)
onDone()
}
}
private fun installed(context: Context): Boolean =
runCatching { context.packageManager.getPackageInfo(SHIZUKU_PACKAGE, 0) }.isSuccess
/** Checked the way the platform checks it; there is no public permission for it. */
fun hasProjectMedia(context: Context): Boolean {
val ops = context.getSystemService(AppOpsManager::class.java) ?: return false
return runCatching {
ops.unsafeCheckOpNoThrow("android:project_media", android.os.Process.myUid(), context.packageName)
}.getOrDefault(AppOpsManager.MODE_IGNORED) == AppOpsManager.MODE_ALLOWED
}
private fun hasSecureSettings(context: Context): Boolean =
context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED
}
@@ -43,6 +43,7 @@ fun AudioChoiceDialog(onUseBluetooth: () -> Unit, onKeepAsking: () -> Unit) {
style = MaterialTheme.typography.bodyMedium,
)
CopyableCommand("adb shell appops set ${BuildConfig.APPLICATION_ID} PROJECT_MEDIA allow")
ShizukuGrantButton()
}
// Stacked full width: three labels this long never fit the dialog's one button row.
Column(Modifier.fillMaxWidth().padding(top = 4.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -166,6 +166,8 @@ private fun Steps(title: String, steps: List<Step>) {
Text(stringResource(it), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
step.command?.let { CopyableCommand(it) }
// One button does both steps, so it sits under the first only.
if (step === USB_AUDIO.first()) ShizukuGrantButton(Modifier.padding(top = 4.dp))
if (step.onClick != null) {
FilledTonalButton(onClick = step.onClick, modifier = Modifier.padding(top = 4.dp)) {
Text(stringResource(step.buttonLabel ?: R.string.guide_open))
@@ -547,7 +547,10 @@ fun SetupGuideScreen(onRequestCallScreening: () -> Unit, onDone: () -> Unit, onl
color = c.onVariant,
style = TextStyle(fontSize = cqSp(4.5f), lineHeight = cqSp(6.5f)),
)
page.command?.let { CopyableCommand(it) }
page.command?.let {
CopyableCommand(it)
ShizukuGrantButton()
}
page.content?.invoke(GuideScale(c, ::cq, ::cqSp))
if (page.permissions != null && alreadyGranted) {
Text(
@@ -0,0 +1,45 @@
package app.seb3thehacker.gearslip.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.shizuku.ShizukuSetup
/**
* Under an adb command: does the same from the phone, for drivers who run Shizuku. Shows nothing
* when Shizuku isn't installed, so everyone else sees the command alone, as before.
*/
@Composable
fun ShizukuGrantButton(modifier: Modifier = Modifier) {
val state by ShizukuSetup.state.collectAsState()
val granted by ShizukuSetup.granted.collectAsState()
val working by ShizukuSetup.working.collectAsState()
// Shizuku may have been started, or the grant done over adb, while Gearslip was away.
LifecycleResumeEffect(Unit) {
ShizukuSetup.refresh()
onPauseOrDispose { }
}
LaunchedEffect(Unit) { ShizukuSetup.refresh() }
if (state == ShizukuSetup.State.MISSING) return
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
when {
granted -> Text(stringResource(R.string.shizuku_done), style = MaterialTheme.typography.bodyMedium)
state == ShizukuSetup.State.STOPPED -> Text(stringResource(R.string.shizuku_stopped), style = MaterialTheme.typography.bodyMedium)
else -> OutlinedButton(onClick = ShizukuSetup::setUp, enabled = !working, modifier = Modifier.fillMaxWidth()) {
Text(stringResource(if (working) R.string.shizuku_working else R.string.shizuku_set_up))
}
}
}
}
+4
View File
@@ -736,6 +736,10 @@
<string name="web_plain_http">This page isn\'t encrypted. Anyone on the same network can see what you send it.</string>
<string name="web_plain_http_stop">Don\'t warn for this site</string>
<string name="web_plain_http_hide">Hide warning</string>
<string name="shizuku_set_up">Set up with Shizuku</string>
<string name="shizuku_working">Setting up…</string>
<string name="shizuku_done">Set up through Shizuku. Nothing more to do here.</string>
<string name="shizuku_stopped">Shizuku is installed but not running. Start it in the Shizuku app, then come back here.</string>
<string name="web_start_page">Start page</string>
<string name="web_fullscreen">Full screen</string>