6 Commits
22 changed files with 243 additions and 129 deletions
+4
View File
@@ -7,6 +7,10 @@
# The following line activates a set of recommended lints for Flutter apps, # The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices. # packages, and plugins designed to encourage good coding practices.
analyzer:
exclude:
- build/**
- android/**
include: package:flutter_lints/flutter.yaml include: package:flutter_lints/flutter.yaml
linter: linter:
+11 -6
View File
@@ -20,25 +20,31 @@ android {
versionCode = flutter.versionCode versionCode = flutter.versionCode
versionName = flutter.versionName versionName = flutter.versionName
// 仅打包 arm64-v8a(与你的 jniLibs 目录匹配) // 仅打包 arm64-v8a
ndk { ndk {
abiFilters.addAll(listOf("arm64-v8a")) abiFilters.addAll(listOf("arm64-v8a"))
} }
} }
// 显式指定 jniLibs 源目录(确保 .so 文件被包含) // 显式指定 jniLibs 源目录
sourceSets { sourceSets {
getByName("main") { getByName("main") {
jniLibs.srcDirs("src/main/jniLibs") jniLibs.srcDirs("src/main/jniLibs")
} }
} }
// ⭐ 关键:打包配置,确保 .so 不被压缩,且处理重复 tasks.withType<Copy> {
if (name.startsWith("merge") && name.endsWith("JniLibFolders")) {
from("src/main/jniLibs")
into("$buildDir/intermediates/merged_jni_libs/debug/out")
}
}
// 打包配置
packagingOptions { packagingOptions {
jniLibs { jniLibs {
useLegacyPackaging = true // 兼容 Android 7.0+ useLegacyPackaging = true
} }
pickFirsts += "**/*.so" // 如有重复则选第一个 pickFirsts += "**/*.so"
} }
buildTypes { buildTypes {
@@ -47,7 +53,6 @@ android {
release { release {
signingConfig = signingConfigs.getByName("debug") signingConfig = signingConfigs.getByName("debug")
// ⭐ 建议开启混淆时保留某些 native 方法(media_kit 会自动处理)
proguardFiles( proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro" "proguard-rules.pro"
+45
View File
@@ -0,0 +1,45 @@
# ============================================================
# media_kit 核心
# ============================================================
-keep class com.media_kit.** { *; }
-keep class com.alexmercerind.** { *; }
-keep class org.mozilla.** { *; }
# 保留所有 native 方法
-keepclasseswithmembernames class * {
native <methods>;
}
# 保留所有 JNI 相关
-keep class * implements java.lang.reflect.Method { *; }
-keep class * extends java.lang.reflect.Method { *; }
# ============================================================
# audio_service 插件
# ============================================================
-keep class com.ryanheise.audioservice.** { *; }
# ============================================================
# Flutter 核心
# ============================================================
-keep class io.flutter.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.embedding.** { *; }
# ============================================================
# 忽略 Google Play Core 缺失类(如果不想添加依赖)
# ============================================================
-dontwarn com.google.android.play.core.**
-keep class com.google.android.play.core.** { *; }
# ============================================================
# 保留 Serializable 支持
# ============================================================
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
+1
View File
@@ -7,6 +7,7 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<application <application
android:name="${applicationName}" android:name="${applicationName}"
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -4,17 +4,66 @@ import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import com.ryanheise.audioservice.AudioServiceActivity import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel
import java.io.File import java.io.File
import android.content.Context
import android.media.AudioManager
class MainActivity : AudioServiceActivity() { class MainActivity : FlutterActivity() {
private val CHANNEL = "com.lxh.qingting_player/file_provider" private val CHANNEL = "com.lxh.qingting_player/file_provider"
override fun onCreate(savedInstanceState: Bundle?) {
// ⭐ 强制加载 libmediakitandroidhelper.so,触发 JNI_OnLoad,缓存 JavaVM
try {
System.loadLibrary("mediakitandroidhelper")
Log.d("MainActivity", "✅ libmediakitandroidhelper loaded")
} catch (e: UnsatisfiedLinkError) {
Log.e("MainActivity", "❌ libmediakitandroidhelper load failed", e)
}
// ⭐ 可选:预加载 libmpv.so(让系统 linker 也可见,增强兼容性)
try {
System.loadLibrary("mpv")
Log.d("MainActivity", "✅ libmpv loaded")
} catch (e: UnsatisfiedLinkError) {
Log.e("MainActivity", "❌ libmpv load failed", e)
}
super.onCreate(savedInstanceState)
requestAudioFocus()
setHighRefreshRate()
}
private fun requestAudioFocus() {
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(
AudioManager.OnAudioFocusChangeListener { focusChange ->
Log.d("MainActivity", "音频焦点变化: $focusChange")
},
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
)
} else {
@Suppress("DEPRECATION")
audioManager.requestAudioFocus(
null,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
)
}
Log.d("MainActivity", "✅ 已请求音频焦点")
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) { override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine) super.configureFlutterEngine(flutterEngine)
// FileProvider MethodChannel for sharing artwork via content:// URI
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
.setMethodCallHandler { call, result -> .setMethodCallHandler { call, result ->
if (call.method == "getContentUri") { if (call.method == "getContentUri") {
@@ -46,20 +95,6 @@ class MainActivity : AudioServiceActivity() {
} }
} }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 🔥 测试 libmpv.so 能否被系统加载
try {
System.loadLibrary("mpv")
Log.e("MPV_TEST", "🔥 libmpv LOAD SUCCESS")
} catch (e: Throwable) {
Log.e("MPV_TEST", "🔥 libmpv LOAD FAILED", e)
}
setHighRefreshRate()
}
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
setHighRefreshRate() setHighRefreshRate()
@@ -77,17 +112,4 @@ class MainActivity : AudioServiceActivity() {
Log.e("QTPlayer", "设置高刷失败: ${e.message}") Log.e("QTPlayer", "设置高刷失败: ${e.message}")
} }
} }
private fun clearRefreshRate() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val params = window.attributes
params.preferredRefreshRate = 0f
window.attributes = params
Log.d("QTPlayer", "恢复默认刷新率")
}
} catch (e: Exception) {
Log.e("QTPlayer", "恢复默认刷新率失败: ${e.message}")
}
}
} }
+1 -1
View File
@@ -20,7 +20,7 @@ pluginManagement {
plugins { plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0" id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.0.1" apply false id("com.android.application") version "9.0.1" apply false
id("org.jetbrains.kotlin.android") version "1.9.0" apply false id("org.jetbrains.kotlin.android") version "2.3.20" apply false
} }
include(":app") include(":app")
+67 -57
View File
@@ -5,6 +5,7 @@ import 'package:media_kit/media_kit.dart';
import 'package:audio_service/audio_service.dart' as audio_service; import 'package:audio_service/audio_service.dart' as audio_service;
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/services.dart';
import 'services/audio_service.dart'; import 'services/audio_service.dart';
import 'services/playback_service.dart'; import 'services/playback_service.dart';
import 'services/app_lifecycle_service.dart'; import 'services/app_lifecycle_service.dart';
@@ -15,8 +16,8 @@ import 'pages/home_page.dart';
import 'pages/player_page.dart'; import 'pages/player_page.dart';
import 'pages/playlist_page.dart'; import 'pages/playlist_page.dart';
import 'widgets/global_mini_player.dart'; import 'widgets/global_mini_player.dart';
import 'utils/navigation.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final stopwatch = Stopwatch(); final stopwatch = Stopwatch();
bool _appInitialized = false; bool _appInitialized = false;
@@ -363,65 +364,74 @@ class _QTPlayerAppState extends State<QTPlayerApp> {
debugPrint( debugPrint(
'🎨 [QTPlayerApp] build #$_buildCount ${stopwatch.elapsedMilliseconds}ms'); '🎨 [QTPlayerApp] build #$_buildCount ${stopwatch.elapsedMilliseconds}ms');
return MaterialApp( // ⭐ 使用 AnnotatedRegion 包裹 MaterialApp,统一控制系统栏样式
title: '清听', return AnnotatedRegion<SystemUiOverlayStyle>(
theme: ThemeData( value: SystemUiOverlayStyle(
brightness: Brightness.dark, statusBarColor: Colors.transparent,
primaryColor: const Color(0xFF7C9A9E), statusBarIconBrightness: Brightness.light,
colorScheme: const ColorScheme.dark( systemNavigationBarColor: const Color(0xFF1A1F1E),
primary: Color(0xFF7C9A9E), systemNavigationBarIconBrightness: Brightness.light,
secondary: Color(0xFFB8D4D0),
surface: Color(0xFF1A1F1E),
onSurface: Colors.white,
),
useMaterial3: true,
), ),
navigatorKey: navigatorKey, child: MaterialApp(
navigatorObservers: [MiniPlayerNavigatorObserver()], title: '清听',
onGenerateRoute: _onGenerateRoute, theme: ThemeData(
builder: (context, child) { brightness: Brightness.dark,
return Stack( primaryColor: const Color(0xFF7C9A9E),
fit: StackFit.expand, colorScheme: const ColorScheme.dark(
children: [ primary: Color(0xFF7C9A9E),
if (child != null) child, secondary: Color(0xFFB8D4D0),
AnimatedBuilder( surface: Color(0xFF1A1F1E),
animation: RouteManager(), onSurface: Colors.white,
builder: (context, _) { ),
final routeManager = RouteManager(); useMaterial3: true,
final shouldShow = routeManager.currentRoute != '/player' && ),
routeManager.currentRoute != '/playlist'; navigatorKey: navigatorKey,
navigatorObservers: [MiniPlayerNavigatorObserver()],
onGenerateRoute: _onGenerateRoute,
builder: (context, child) {
return Stack(
fit: StackFit.expand,
children: [
if (child != null) child,
AnimatedBuilder(
animation: RouteManager(),
builder: (context, _) {
final routeManager = RouteManager();
final shouldShow = routeManager.currentRoute != '/player' &&
routeManager.currentRoute != '/playlist';
return AnimatedSwitcher( return AnimatedSwitcher(
duration: const Duration(milliseconds: 300), duration: const Duration(milliseconds: 300),
switchInCurve: Curves.easeOut, switchInCurve: Curves.easeOut,
switchOutCurve: Curves.easeIn, switchOutCurve: Curves.easeIn,
transitionBuilder: (child, animation) { transitionBuilder: (child, animation) {
return FadeTransition( return FadeTransition(
opacity: animation, opacity: animation,
child: SlideTransition( child: SlideTransition(
position: Tween<Offset>( position: Tween<Offset>(
begin: const Offset(0, 0.1), begin: const Offset(0, 0.1),
end: Offset.zero, end: Offset.zero,
).animate(animation), ).animate(animation),
child: child, child: child,
),
);
},
child: shouldShow
? const Align(
key: ValueKey('mini_player_visible'),
alignment: Alignment.bottomCenter,
child: GlobalMiniPlayer(),
)
: const SizedBox.shrink(
key: ValueKey('mini_player_hidden'),
), ),
); );
}, },
), child: shouldShow
], ? const Align(
); key: ValueKey('mini_player_visible'),
}, alignment: Alignment.bottomCenter,
child: GlobalMiniPlayer(),
)
: const SizedBox.shrink(
key: ValueKey('mini_player_hidden'),
),
);
},
),
],
);
},
),
); );
} }
} }
+5 -21
View File
@@ -779,6 +779,7 @@ class AudioService extends ChangeNotifier {
debugPrint('💾 [AudioService] playback state saved'); debugPrint('💾 [AudioService] playback state saved');
} }
/// 恢复播放状态
/// 恢复播放状态 /// 恢复播放状态
Future<bool> restorePlaybackState() async { Future<bool> restorePlaybackState() async {
final state = await _db.getPlaybackState(); final state = await _db.getPlaybackState();
@@ -802,9 +803,7 @@ class AudioService extends ChangeNotifier {
_queue = queue; _queue = queue;
_currentIndex = state['current_index'] as int; _currentIndex = state['current_index'] as int;
if (_currentIndex < 0 || _currentIndex >= _queue.length) { if (_currentIndex >= _queue.length) _currentIndex = 0;
_currentIndex = 0;
}
final modeStr = state['play_mode'] as String? ?? 'sequential'; final modeStr = state['play_mode'] as String? ?? 'sequential';
_playMode = modeStr == 'sequential' _playMode = modeStr == 'sequential'
@@ -814,20 +813,6 @@ class AudioService extends ChangeNotifier {
: PlayMode.shuffle; : PlayMode.shuffle;
_currentPlaylistId = state['current_playlist_id'] as String?; _currentPlaylistId = state['current_playlist_id'] as String?;
// ⭐⭐⭐ 关键修复:重建 _shuffledIndices 和 _shuffledIndex ⭐⭐⭐
if (_playMode == PlayMode.shuffle) {
_shuffledIndices = List.generate(_queue.length, (i) => i);
_shuffledIndices.shuffle();
_shuffledIndex = _shuffledIndices.indexOf(_currentIndex);
if (_shuffledIndex == -1) {
_shuffledIndex = 0;
_currentIndex = _shuffledIndices[0];
}
} else {
_shuffledIndices = List.generate(_queue.length, (i) => i);
_shuffledIndex = _currentIndex;
}
// 保存待恢复的进度 // 保存待恢复的进度
final savedPos = state['position_ms'] as int? ?? 0; final savedPos = state['position_ms'] as int? ?? 0;
_pendingSeekPosition = Duration(milliseconds: savedPos); _pendingSeekPosition = Duration(milliseconds: savedPos);
@@ -836,11 +821,10 @@ class AudioService extends ChangeNotifier {
_currentSong = song; _currentSong = song;
_onSongChanged?.call(song); _onSongChanged?.call(song);
debugPrint('♻️ [AudioService] playback state restored: ' debugPrint(
'queue=${_queue.length}, index=$_currentIndex, ' '♻️ [AudioService] playback state restored: ${song.title} - ${song.artist}');
'song=${song.title}, mode=$_playMode');
// ⭐ 加载音频但不自动播放 // ⭐ 关键:加载音频但不自动播放
await _loadRestoredPlayback(); await _loadRestoredPlayback();
return true; return true;
+3
View File
@@ -0,0 +1,3 @@
import 'package:flutter/material.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
+5 -5
View File
@@ -2,6 +2,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../services/audio_service.dart'; import '../services/audio_service.dart';
import '../utils/navigation.dart'; // ⭐ 导入 navigatorKey
class GlobalMiniPlayer extends StatelessWidget { class GlobalMiniPlayer extends StatelessWidget {
const GlobalMiniPlayer({super.key}); const GlobalMiniPlayer({super.key});
@@ -45,10 +46,9 @@ class GlobalMiniPlayer extends StatelessWidget {
color: Colors.transparent, color: Colors.transparent,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
// ⭐ 使用 Navigator.of(context) 替代 navigatorKey // ⭐ 使用 navigatorKey 直接跳转
Navigator.of(context).pushNamed('/player'); navigatorKey.currentState?.pushNamed('/player');
}, },
// ⭐ 替换弃用的 withOpacity 为 withValues
highlightColor: Colors.white.withValues(alpha: 0.05), highlightColor: Colors.white.withValues(alpha: 0.05),
splashColor: Colors.white.withValues(alpha: 0.1), splashColor: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
@@ -123,8 +123,8 @@ class GlobalMiniPlayer extends StatelessWidget {
size: 24, size: 24,
), ),
onPressed: () { onPressed: () {
// ⭐ 使用 Navigator.of(context) // ⭐ 使用 navigatorKey 直接跳转
Navigator.of(context).pushNamed('/playlist'); navigatorKey.currentState?.pushNamed('/playlist');
}, },
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
+49 -9
View File
@@ -332,10 +332,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "0.12.19" version: "0.12.20"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
@@ -353,21 +353,61 @@ packages:
source: hosted source: hosted
version: "1.2.6" version: "1.2.6"
media_kit_libs_android_audio: media_kit_libs_android_audio:
dependency: "direct main" dependency: transitive
description: description:
name: media_kit_libs_android_audio name: media_kit_libs_android_audio
sha256: "8f8f9759e537e12d66f08bc4d5279eb1bb21a0ccc519ff3442c68a9f3b6dd68b" sha256: "8f8f9759e537e12d66f08bc4d5279eb1bb21a0ccc519ff3442c68a9f3b6dd68b"
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "1.3.8" version: "1.3.8"
media_kit_libs_audio:
dependency: "direct main"
description:
name: media_kit_libs_audio
sha256: "81bf506c234e81e3ec536ba72f8f700a928543c14c345220210cae0411636316"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.7"
media_kit_libs_ios_audio:
dependency: transitive
description:
name: media_kit_libs_ios_audio
sha256: "78ccf04e27d6b4ba00a355578ccb39b772f00d48269a6ac3db076edf2d51934f"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.4"
media_kit_libs_linux:
dependency: transitive
description:
name: media_kit_libs_linux
sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.2.1"
media_kit_libs_macos_audio:
dependency: transitive
description:
name: media_kit_libs_macos_audio
sha256: "3be21844df98f286de32808592835073cdef2c1a10078bac135da790badca950"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.4"
media_kit_libs_windows_audio:
dependency: transitive
description:
name: media_kit_libs_windows_audio
sha256: c2fd558cc87b9d89a801141fcdffe02e338a3b21a41a18fbd63d5b221a1b8e53
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.9"
meta: meta:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "1.18.0" version: "1.19.0"
mime: mime:
dependency: transitive dependency: transitive
description: description:
@@ -729,10 +769,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "0.7.11" version: "0.7.12"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@@ -769,10 +809,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "2.2.0" version: "2.4.2"
vm_service: vm_service:
dependency: transitive dependency: transitive
description: description:
+1 -1
View File
@@ -31,7 +31,7 @@ dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
media_kit: 1.2.6 media_kit: 1.2.6
media_kit_libs_android_audio: 1.3.8 media_kit_libs_audio: ^1.0.7
shared_preferences: 2.2.2 shared_preferences: 2.2.2
provider: ^6.1.2 provider: ^6.1.2
dio: ^5.4.0 # HTTP 客户端 dio: ^5.4.0 # HTTP 客户端