init
No files matched your search
@@ -0,0 +1,6 @@
|
||||
/src/main/**/generated
|
||||
/src/main/jniLibs/**/*.so
|
||||
/src/main/assets/tauri.conf.json
|
||||
/tauri.build.gradle.kts
|
||||
/proguard-tauri.pro
|
||||
/tauri.properties
|
||||
@@ -0,0 +1,92 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("rust")
|
||||
}
|
||||
|
||||
val tauriProperties = Properties().apply {
|
||||
val propFile = file("tauri.properties")
|
||||
if (propFile.exists()) {
|
||||
propFile.inputStream().use { load(it) }
|
||||
}
|
||||
}
|
||||
|
||||
// 签名信息放在 app/keystore.properties(已被 .gitignore 忽略),缺失时 release 仍输出未签名 APK
|
||||
val signingProperties = Properties().apply {
|
||||
val propFile = file("keystore.properties")
|
||||
if (propFile.exists()) {
|
||||
propFile.inputStream().use { load(it) }
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdk = 36
|
||||
namespace = "music.lfeng.me"
|
||||
defaultConfig {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "false"
|
||||
applicationId = "music.lfeng.me"
|
||||
// tauri-plugin-native-audio 要求 API 26+(Android 8.0,插件 README / manifest 声明)
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt()
|
||||
versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0")
|
||||
}
|
||||
signingConfigs {
|
||||
if (signingProperties.containsKey("key.storeFile")) {
|
||||
create("release") {
|
||||
storeFile = file(signingProperties.getProperty("key.storeFile"))
|
||||
storePassword = signingProperties.getProperty("key.storePassword")
|
||||
keyAlias = signingProperties.getProperty("key.alias")
|
||||
keyPassword = signingProperties.getProperty("key.storePassword")
|
||||
}
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "true"
|
||||
isDebuggable = true
|
||||
isJniDebuggable = true
|
||||
isMinifyEnabled = false
|
||||
packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
|
||||
}
|
||||
}
|
||||
getByName("release") {
|
||||
isMinifyEnabled = true
|
||||
signingConfig = signingConfigs.findByName("release")
|
||||
?: signingConfigs.getByName("debug")
|
||||
proguardFiles(
|
||||
*fileTree(".") { include("**/*.pro") }
|
||||
.plus(getDefaultProguardFile("proguard-android-optimize.txt"))
|
||||
.toList().toTypedArray()
|
||||
)
|
||||
}
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
rust {
|
||||
rootDirRel = "../../../"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.webkit:webkit:1.14.0")
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("androidx.activity:activity-ktx:1.10.1")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.10.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.4")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
|
||||
}
|
||||
|
||||
apply(from = "tauri.build.gradle.kts")
|
||||
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- 存储选型 spike / M1 曲库扫描(PLAN.md §2 权限清单)
|
||||
注意:READ_EXTERNAL_STORAGE **不能**加 maxSdkVersion=32——requestPermissions
|
||||
要求所请求的权限已在清单声明,缺声明会让整批申请静默失败(M1-a 真机踩点);
|
||||
API 33+ 上该旧权限由系统自动拒绝,不影响 READ_MEDIA_AUDIO 授予。 -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
|
||||
<!-- M4 UAC:前台服务保活(锁屏/后台继续 iso 传输)+ wake lock 防 CPU 休眠断流 -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<!-- AndroidTV support -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
|
||||
<!-- M4 UAC:USB Host(外接 DAC bit-perfect,PLAN §3.4)。
|
||||
USB 设备访问权限不走 manifest 危险权限,由 UsbManager.requestPermission 系统弹窗授予。 -->
|
||||
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
|
||||
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.lfmusic"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:launchMode="singleTask"
|
||||
android:label="@string/main_activity_title"
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<!-- AndroidTV support -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
|
||||
<!-- M4 UAC 播放保活前台服务 -->
|
||||
<service
|
||||
android:name=".UacPlaybackService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,24 @@
|
||||
package music.lfeng.me
|
||||
|
||||
import android.os.Bundle
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebView
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
|
||||
class MainActivity : TauriActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
/** JS 桥:主界面按系统返回时最小化到桌面(音乐继续播),而非退出应用 */
|
||||
override fun onWebViewCreate(webView: WebView) {
|
||||
super.onWebViewCreate(webView)
|
||||
webView.addJavascriptInterface(object {
|
||||
@JavascriptInterface
|
||||
fun minimize() {
|
||||
runOnUiThread { moveTaskToBack(true) }
|
||||
}
|
||||
}, "LFAndroid")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package music.lfeng.me
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import app.tauri.PermissionState
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.Permission
|
||||
import app.tauri.annotation.PermissionCallback
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
|
||||
/**
|
||||
* 曲库媒体权限桥(LFMusic PLAN M1-a:应用内运行时申请)。
|
||||
*
|
||||
* 注册链:lib.rs::media_plugin → register_android_plugin("music.lfeng.me", "MediaPlugin")
|
||||
* JS:checkPermissions('media') / requestPermissions('media') → { audio: "GRANTED"|... }
|
||||
*
|
||||
* **双别名按 API 分流(M1-a 真机踩点)**:
|
||||
* - API 33+:只用 `audio`(READ_MEDIA_AUDIO)。READ_EXTERNAL_STORAGE 对 targetSdk33+
|
||||
* 应用是"声明即永久拒绝、连弹窗都不出"的废弃权限——**绝不能与现代权限捆在同一
|
||||
* 别名**,否则组合状态永远 denied、request 秒回拒绝(35ms 无弹窗死循环)。
|
||||
* - API ≤32:用 `legacyStorage`(READ_EXTERNAL_STORAGE),旧系统唯一有效路径。
|
||||
*/
|
||||
const val AUDIO_MODERN = "audio"
|
||||
const val AUDIO_LEGACY = "legacyStorage"
|
||||
|
||||
@TauriPlugin(
|
||||
permissions = [
|
||||
Permission(strings = [Manifest.permission.READ_MEDIA_AUDIO], alias = AUDIO_MODERN),
|
||||
Permission(strings = [Manifest.permission.READ_EXTERNAL_STORAGE], alias = AUDIO_LEGACY)
|
||||
]
|
||||
)
|
||||
class MediaPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
|
||||
private fun activeAlias(): String =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) AUDIO_MODERN else AUDIO_LEGACY
|
||||
|
||||
@Command
|
||||
override fun checkPermissions(invoke: Invoke) {
|
||||
Log.d(TAG, "checkPermissions called alias=${activeAlias()}")
|
||||
try {
|
||||
resolveState(invoke)
|
||||
} catch (ex: Exception) {
|
||||
Log.e(TAG, "checkPermissions failed", ex)
|
||||
invoke.reject("checkPermissions: ${ex.message}")
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
override fun requestPermissions(invoke: Invoke) {
|
||||
val alias = activeAlias()
|
||||
Log.d(TAG, "requestPermissions called alias=$alias state=${getPermissionState(alias)}")
|
||||
try {
|
||||
if (getPermissionState(alias) == PermissionState.GRANTED) {
|
||||
resolveState(invoke)
|
||||
return
|
||||
}
|
||||
requestPermissionForAlias(alias, invoke, "audioPermissionCallback")
|
||||
Log.d(TAG, "requestPermissionForAlias dispatched for $alias")
|
||||
} catch (ex: Exception) {
|
||||
Log.e(TAG, "requestPermissions failed", ex)
|
||||
invoke.reject("requestPermissions: ${ex.message}")
|
||||
}
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private fun audioPermissionCallback(invoke: Invoke) {
|
||||
Log.d(TAG, "permission callback, state=${getPermissionState(activeAlias())}")
|
||||
resolveState(invoke)
|
||||
}
|
||||
|
||||
private fun resolveState(invoke: Invoke) {
|
||||
val json = JSObject()
|
||||
json.put("audio", getPermissionState(activeAlias()).toString())
|
||||
Log.d(TAG, "resolve state=$json")
|
||||
invoke.resolve(json)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MediaPlugin"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package music.lfeng.me
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* UAC 播放前台服务(M4:锁屏/后台保活)。
|
||||
*
|
||||
* 为什么需要:UAC iso 传输走应用进程,ColorOS 等激进省电策略会把后台应用冻结,
|
||||
* USB 传输停摆 → DAC 断流。前台服务 + partial wake lock 保住进程优先级与 CPU。
|
||||
*
|
||||
* 生命周期(由 UsbPlugin.setPlaybackActive 驱动):
|
||||
* - uac 播放启动 → startPlaybackActive(true) → startForegroundService
|
||||
* - 停止/结束/出错 → setPlaybackActive(false) → stopSelf
|
||||
*
|
||||
* foregroundServiceType="mediaPlayback"(API 29+ 必须;API 34+ 需
|
||||
* FOREGROUND_SERVICE_MEDIA_PLAYBACK 权限,已在 manifest 声明)。
|
||||
*/
|
||||
class UacPlaybackService : Service() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "UacPlaybackService"
|
||||
const val CHANNEL_ID = "uac_playback"
|
||||
const val NOTIFICATION_ID = 40001
|
||||
|
||||
const val ACTION_START = "music.lfeng.me.uac.PLAYBACK_START"
|
||||
const val ACTION_STOP = "music.lfeng.me.uac.PLAYBACK_STOP"
|
||||
|
||||
fun start(context: Context) {
|
||||
val intent = Intent(context, UacPlaybackService::class.java).setAction(ACTION_START)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.startService(
|
||||
Intent(context, UacPlaybackService::class.java).setAction(ACTION_STOP)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_STOP -> {
|
||||
Log.i(TAG, "stop")
|
||||
releaseWakeLock()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
else -> {
|
||||
Log.i(TAG, "start (UAC 播放保活)")
|
||||
startInForeground()
|
||||
acquireWakeLock()
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private fun startInForeground() {
|
||||
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"USB DAC 播放",
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply { setShowBadge(false) }
|
||||
)
|
||||
}
|
||||
val contentIntent = PendingIntent.getActivity(
|
||||
this, 0,
|
||||
packageManager.getLaunchIntentForPackage(packageName)
|
||||
?: Intent().setPackage(packageName),
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
val notification: Notification =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Notification.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("USB DAC 直出中")
|
||||
.setContentText("bit-perfect 输出 · 点击返回应用")
|
||||
.setSmallIcon(android.R.drawable.stat_sys_headset)
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
Notification.Builder(this)
|
||||
.setContentTitle("USB DAC 直出中")
|
||||
.setContentText("bit-perfect 输出 · 点击返回应用")
|
||||
.setSmallIcon(android.R.drawable.stat_sys_headset)
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
|
||||
)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
}
|
||||
|
||||
private fun acquireWakeLock() {
|
||||
if (wakeLock?.isHeld == true) return
|
||||
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lfmusic:uac_playback").apply {
|
||||
setReferenceCounted(false)
|
||||
acquire(4 * 60 * 60 * 1000L) // 上限 4h,正常由 stop 释放
|
||||
}
|
||||
Log.i(TAG, "partial wake lock acquired")
|
||||
}
|
||||
|
||||
private fun releaseWakeLock() {
|
||||
wakeLock?.let {
|
||||
if (it.isHeld) it.release()
|
||||
}
|
||||
wakeLock = null
|
||||
Log.i(TAG, "wake lock released")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
releaseWakeLock()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package music.lfeng.me
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSArray
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
|
||||
/**
|
||||
* USB Host 桥(LFMusic PLAN M4:UAC 播放的 Kotlin 侧)。
|
||||
*
|
||||
* 职责(Flick MainActivity.kt 同款模式,flutter→tauri 适配):
|
||||
* 1. listDevices —— UsbManager.deviceList 枚举 + UAC 识别(class 0x01)
|
||||
* 2. requestPermission —— UsbManager.requestPermission 系统弹窗(广播回调,非
|
||||
* Tauri Permission 注解体系——USB host 权限是 intent 流程,不是 manifest 危险权限)
|
||||
* 3. openDevice —— openDevice() 返回 UsbDeviceConnection,**保存在本插件内
|
||||
* 保活**,把 fileDescriptor 交给 JS → Rust `uac_open`(dup + libusb wrap_sys_device)
|
||||
* 4. closeDevice —— 关闭保活连接(Rust 侧已 dup,不影响其句柄存活)
|
||||
* 5. 热插拔 —— ATTACH/DETACH 广播 → trigger("usb-attach"/"usb-detach")
|
||||
*
|
||||
* **踩点(照抄 Flick 2026 现役实现)**:
|
||||
* - PendingIntent 必须 FLAG_MUTABLE(系统要往里塞 EXTRA_PERMISSION_GRANTED 等 extras)
|
||||
* - API 33+ 注册 receiver 必须 RECEIVER_NOT_EXPORTED
|
||||
* - UsbDeviceConnection 必须保活(与 Flick 一致)
|
||||
* - Invoke 取参用 parseArgs + @InvocationArg 数据类(Invoke 无 getString 方法)
|
||||
*/
|
||||
@TauriPlugin
|
||||
class UsbPlugin(private val activity: Activity) : Plugin(activity) {
|
||||
|
||||
companion object {
|
||||
const val TAG = "UsbPlugin"
|
||||
const val ACTION_USB_PERMISSION = "music.lfeng.me.USB_PERMISSION"
|
||||
}
|
||||
|
||||
/** invoke 取参:getArgs() 返回 JSObject(JSONObject 子类) */
|
||||
private fun Invoke.argDeviceName(): String =
|
||||
try {
|
||||
this.getArgs().getString("deviceName") ?: ""
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
|
||||
private val connections = LinkedHashMap<String, UsbDeviceConnection>()
|
||||
private val pendingPermission = HashMap<String, Invoke>()
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
ACTION_USB_PERMISSION -> {
|
||||
val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as? UsbDevice
|
||||
}
|
||||
val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
|
||||
val name = device?.deviceName ?: "unknown"
|
||||
Log.i(TAG, "USB permission result: device=$name granted=$granted")
|
||||
pendingPermission.remove(name)?.let { invoke ->
|
||||
val ret = JSObject()
|
||||
ret.put("granted", granted as Any)
|
||||
ret.put("deviceName", name)
|
||||
if (!granted) ret.put("error", "用户拒绝了 USB 访问授权")
|
||||
invoke.resolve(ret)
|
||||
}
|
||||
}
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
|
||||
val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as? UsbDevice
|
||||
}
|
||||
Log.i(TAG, "USB attached: ${device?.deviceName}")
|
||||
device?.let { trigger("usb-attach", deviceToJs(it)) }
|
||||
}
|
||||
UsbManager.ACTION_USB_DEVICE_DETACHED -> {
|
||||
val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as? UsbDevice
|
||||
}
|
||||
Log.i(TAG, "USB detached: ${device?.deviceName}")
|
||||
device?.let {
|
||||
connections.remove(it.deviceName)?.close()
|
||||
trigger("usb-detach", deviceToJs(it))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(ACTION_USB_PERMISSION)
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
activity.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
||||
} else {
|
||||
activity.registerReceiver(receiver, filter)
|
||||
}
|
||||
}
|
||||
|
||||
private fun usbManager(): UsbManager =
|
||||
activity.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
|
||||
private fun deviceToJs(device: UsbDevice): JSObject {
|
||||
val o = JSObject()
|
||||
o.put("deviceName", device.deviceName)
|
||||
o.put("vendorId", device.vendorId as Any)
|
||||
o.put("productId", device.productId as Any)
|
||||
o.put("productName", device.productName ?: "")
|
||||
o.put("manufacturerName", device.manufacturerName ?: "")
|
||||
// 未授权时读 serialNumber 会被 UsbSerialReader 拒绝(SecurityException),
|
||||
// 授权后 openDevice 时再取
|
||||
o.put("serialNumber", try { device.serialNumber ?: "" } catch (_: Exception) { "" })
|
||||
o.put("hasPermission", usbManager().hasPermission(device) as Any)
|
||||
// UAC 识别:任一接口 class == AUDIO(0x01);protocol 0x20 = UAC 2.0
|
||||
var isUac = false
|
||||
var isUac2 = false
|
||||
for (i in 0 until device.interfaceCount) {
|
||||
val iface = device.getInterface(i)
|
||||
if (iface.interfaceClass == UsbConstants.USB_CLASS_AUDIO) {
|
||||
isUac = true
|
||||
if (iface.interfaceProtocol == 0x20) isUac2 = true
|
||||
}
|
||||
}
|
||||
o.put("isUac", isUac as Any)
|
||||
o.put("isUac2", isUac2 as Any)
|
||||
return o
|
||||
}
|
||||
|
||||
@Command
|
||||
fun listDevices(invoke: Invoke) {
|
||||
try {
|
||||
val manager = usbManager()
|
||||
val arr = JSArray()
|
||||
for ((_, device) in manager.deviceList) {
|
||||
arr.put(deviceToJs(device))
|
||||
}
|
||||
val ret = JSObject()
|
||||
ret.put("devices", arr)
|
||||
invoke.resolve(ret)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "listDevices failed", e)
|
||||
invoke.reject("listDevices: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun requestPermission(invoke: Invoke) {
|
||||
try {
|
||||
val name = invoke.argDeviceName()
|
||||
if (name.isEmpty()) return invoke.reject("缺少 deviceName")
|
||||
val manager = usbManager()
|
||||
val device = manager.deviceList[name]
|
||||
?: return invoke.reject("USB 设备不存在: $name")
|
||||
if (manager.hasPermission(device)) {
|
||||
val ret = JSObject()
|
||||
ret.put("granted", true as Any)
|
||||
ret.put("deviceName", name)
|
||||
invoke.resolve(ret)
|
||||
return
|
||||
}
|
||||
// 同名请求进行中:换 invoke(后到者赢)
|
||||
pendingPermission[name] = invoke
|
||||
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
PendingIntent.FLAG_MUTABLE
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val intent = Intent(ACTION_USB_PERMISSION).setPackage(activity.packageName)
|
||||
val pendingIntent = PendingIntent.getBroadcast(activity, 0, intent, flags)
|
||||
manager.requestPermission(device, pendingIntent)
|
||||
Log.i(TAG, "requestPermission dispatched for $name")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "requestPermission failed", e)
|
||||
invoke.reject("requestPermission: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun openDevice(invoke: Invoke) {
|
||||
try {
|
||||
val name = invoke.argDeviceName()
|
||||
if (name.isEmpty()) return invoke.reject("缺少 deviceName")
|
||||
val manager = usbManager()
|
||||
val device = manager.deviceList[name]
|
||||
?: return invoke.reject("USB 设备不存在: $name")
|
||||
if (!manager.hasPermission(device)) {
|
||||
return invoke.reject("USB 设备未授权,请先 requestPermission: $name")
|
||||
}
|
||||
val connection = connections[name] ?: manager.openDevice(device)
|
||||
if (connection == null) {
|
||||
return invoke.reject("openDevice 失败(设备可能已被占用): $name")
|
||||
}
|
||||
connections[name] = connection
|
||||
val fd = connection.fileDescriptor
|
||||
if (fd < 0) {
|
||||
return invoke.reject("fileDescriptor 无效: $name")
|
||||
}
|
||||
Log.i(TAG, "openDevice ok: $name fd=$fd vid=0x%04x pid=0x%04x"
|
||||
.format(device.vendorId, device.productId))
|
||||
val ret = deviceToJs(device)
|
||||
ret.put("fd", fd as Any)
|
||||
invoke.resolve(ret)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "openDevice failed", e)
|
||||
invoke.reject("openDevice: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun closeDevice(invoke: Invoke) {
|
||||
try {
|
||||
val name = invoke.argDeviceName()
|
||||
if (name.isEmpty()) return invoke.reject("缺少 deviceName")
|
||||
val conn = connections.remove(name)
|
||||
conn?.close()
|
||||
Log.i(TAG, "closeDevice: $name (had=${conn != null})")
|
||||
invoke.resolve()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "closeDevice failed", e)
|
||||
invoke.reject("closeDevice: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UAC 播放前台服务开关(M4 锁屏/后台保活)。
|
||||
* active=true 启动前台服务(通知+wake lock),false 停止。
|
||||
*/
|
||||
@Command
|
||||
fun setPlaybackActive(invoke: Invoke) {
|
||||
try {
|
||||
val args = invoke.getArgs()
|
||||
val active = args.optBoolean("active", false)
|
||||
if (active) {
|
||||
UacPlaybackService.start(activity)
|
||||
} else {
|
||||
UacPlaybackService.stop(activity)
|
||||
}
|
||||
Log.i(TAG, "setPlaybackActive: $active")
|
||||
invoke.resolve()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "setPlaybackActive failed", e)
|
||||
invoke.reject("setPlaybackActive: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
try {
|
||||
activity.unregisterReceiver(receiver)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
for ((_, conn) in connections) {
|
||||
try {
|
||||
conn.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
connections.clear()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Hello World!"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintLeft_toLeftOf="parent"
|
||||
app:layout_constraintRight_toRightOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@mipmap/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1008 B |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.lfmusic" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">LFMusic</string>
|
||||
<string name="main_activity_title">LFMusic</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.lfmusic" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
LFMusic PLAN §2 明文清单:飞牛 LAN(http://)、遥控通道(ws://)、
|
||||
本机流代理(http://127.0.0.1)全部依赖明文放行。
|
||||
LAN 地址随 DHCP 变化、无法用 domain-config 精确圈定,故 base-config 放行;
|
||||
与计划接受的「局域网明文传输」威胁模型一致(MUSIC_REMOTE_PLAN §3.4 P0 结论)。
|
||||
-->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="true" />
|
||||
</network-security-config>
|
||||