Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat: android PIP (#1905)

遥遥紫荆80871b03e665
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index fc8b0124..8dbe3c03 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -13,6 +13,8 @@
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
+ android:supportsPictureInPicture="true"
+ android:resizeableActivity="true"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
diff --git a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
index e12028e1..323d5365 100644
--- a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
@@ -1,11 +1,20 @@
package com.example.kazumi
+import android.app.PendingIntent
import android.content.Intent
+import android.content.IntentFilter
+import android.content.BroadcastReceiver
+import android.content.pm.PackageManager
+import android.app.RemoteAction
import android.os.Build
+import android.os.Bundle
import android.os.StatFs
import android.net.Uri
-import android.os.Bundle
+import android.app.PictureInPictureParams
+import android.graphics.drawable.Icon
+import android.util.Rational
import androidx.annotation.NonNull
+import androidx.core.content.ContextCompat
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import com.ryanheise.audioservice.AudioServiceActivity
@@ -13,10 +22,45 @@ import com.ryanheise.audioservice.AudioServiceActivity
class MainActivity: AudioServiceActivity() {
private val CHANNEL = "com.predidit.kazumi/intent"
private val STORAGE_CHANNEL = "com.predidit.kazumi/storage"
+ private val PIP_CHANNEL = "com.predidit.kazumi/pip"
+ private var intentChannel: MethodChannel? = null
+ private var pipChannel: MethodChannel? = null
+
+ private var pipIsPlaying = false
+ private var pipDanmakuEnabled = false
+ private var pipActionReceiverRegistered = false
+ private var autoEnterPipOnHomeGesture = false
+ private var pipInPlayerPage = false
+
+ private val actionPipPlayPause = "com.predidit.kazumi.pip.PLAY_PAUSE"
+ private val actionPipForward = "com.predidit.kazumi.pip.FORWARD"
+ private val actionPipToggleDanmaku = "com.predidit.kazumi.pip.TOGGLE_DANMAKU"
+
+ private val pipActionReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: android.content.Context?, intent: Intent?) {
+ val action = intent?.action ?: return
+ when (action) {
+ actionPipPlayPause -> notifyFlutterPipAction("play_pause")
+ actionPipForward -> notifyFlutterPipAction("forward")
+ actionPipToggleDanmaku -> notifyFlutterPipAction("toggle_danmaku")
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ registerPipActionReceiverIfNeeded()
+ }
+
+ override fun onDestroy() {
+ unregisterPipActionReceiverIfNeeded()
+ super.onDestroy()
+ }
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
- MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
+ intentChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
+ intentChannel?.setMethodCallHandler { call, result ->
if (call.method == "openWithMime") {
val url = call.argument<String>("url")
val mimeType = call.argument<String>("mimeType")
@@ -46,6 +90,33 @@ class MainActivity: AudioServiceActivity() {
result.notImplemented()
}
}
+
+ pipChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, PIP_CHANNEL)
+ pipChannel?.setMethodCallHandler { call, result ->
+ if (call.method == "isPictureInPictureSupported") {
+ result.success(isPictureInPictureSupported())
+ } else if (call.method == "enterPictureInPictureMode") {
+ val width = call.argument<Int>("width") ?: 16
+ val height = call.argument<Int>("height") ?: 9
+ val entered = enterPictureInPicture(width, height)
+ result.success(entered)
+ } else if (call.method == "updatePictureInPictureActions") {
+ val playing = call.argument<Boolean>("playing") ?: false
+ val danmakuEnabled = call.argument<Boolean>("danmakuEnabled") ?: false
+ updatePictureInPictureActions(playing, danmakuEnabled)
+ result.success(true)
+ } else if (call.method == "setAndroidAutoEnterPIPEnabled") {
+ autoEnterPipOnHomeGesture = call.argument<Boolean>("enabled") ?: false
+ refreshPictureInPictureParamsIfNeeded()
+ result.success(true)
+ } else if (call.method == "setAndroidPIPInPlayerPage") {
+ pipInPlayerPage = call.argument<Boolean>("inPlayerPage") ?: false
+ refreshPictureInPictureParamsIfNeeded()
+ result.success(true)
+ } else {
+ result.notImplemented()
+ }
+ }
}
private fun openWithMime(url: String, mimeType: String) {
@@ -67,6 +138,154 @@ class MainActivity: AudioServiceActivity() {
return Build.VERSION.SDK_INT
}
+ private fun isPictureInPictureSupported(): Boolean {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
+ return false
+ }
+ return packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
+ }
+
+ private fun enterPictureInPicture(width: Int, height: Int): Boolean {
+ if (!isPictureInPictureSupported()) {
+ return false
+ }
+ if (isInPictureInPictureMode) {
+ return true
+ }
+ return enterPictureInPictureMode(buildPictureInPictureParams(width, height))
+ }
+
+ private fun updatePictureInPictureActions(
+ playing: Boolean,
+ danmakuEnabled: Boolean
+ ) {
+ if (!isPictureInPictureSupported()) {
+ return
+ }
+ pipIsPlaying = playing
+ pipDanmakuEnabled = danmakuEnabled
+ refreshPictureInPictureParamsIfNeeded()
+ }
+
+ private fun buildPictureInPictureParams(width: Int = 16, height: Int = 9): PictureInPictureParams {
+ val safeWidth = if (width > 0) width else 16
+ val safeHeight = if (height > 0) height else 9
+ val actions = buildPipActions()
+ val builder = PictureInPictureParams.Builder()
+ .setAspectRatio(Rational(safeWidth, safeHeight))
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ builder.setAutoEnterEnabled(autoEnterPipOnHomeGesture && pipInPlayerPage)
+ builder.setSeamlessResizeEnabled(false)
+ }
+ if (actions.isNotEmpty()) {
+ builder.setActions(actions)
+ }
+ return builder.build()
+ }
+
+ private fun refreshPictureInPictureParamsIfNeeded() {
+ if (!isPictureInPictureSupported()) {
+ return
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ setPictureInPictureParams(buildPictureInPictureParams())
+ }
+ }
+
+ private fun buildPipActions(): List<RemoteAction> {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
+ return emptyList()
+ }
+
+ val allActions = mutableListOf<RemoteAction>(
+ createPipAction(
+ action = actionPipToggleDanmaku,
+ requestCode = 1003,
+ iconRes = if (pipDanmakuEnabled) R.drawable.ic_pip_danmaku_on else R.drawable.ic_pip_danmaku_off,
+ title = if (pipDanmakuEnabled) "Danmaku On" else "Danmaku Off",
+ description = if (pipDanmakuEnabled) "Turn off danmaku" else "Turn on danmaku",
+ enabled = true
+ ),
+ createPipAction(
+ action = actionPipPlayPause,
+ requestCode = 1001,
+ iconRes = if (pipIsPlaying) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play,
+ title = if (pipIsPlaying) "Pause" else "Play",
+ description = if (pipIsPlaying) "Pause playback" else "Play playback",
+ enabled = true
+ ),
+ createPipAction(
+ action = actionPipForward,
+ requestCode = 1002,
+ iconRes = R.drawable.ic_pip_forward_80,
+ title = "Forward",
+ description = "Forward by custom seconds",
+ enabled = true
+ )
+ )
+
+ val maxActions = maxNumPictureInPictureActions
+ if (allActions.size > maxActions) {
+ allActions.subList(maxActions, allActions.size).clear()
+ }
+ return allActions
+ }
+
+ private fun createPipAction(
+ action: String,
+ requestCode: Int,
+ iconRes: Int,
+ title: String,
+ description: String,
+ enabled: Boolean
+ ): RemoteAction {
+ val intent = Intent(action).setPackage(packageName)
+ val pendingIntent = PendingIntent.getBroadcast(
+ this,
+ requestCode,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ return RemoteAction(
+ Icon.createWithResource(this, iconRes),
+ title,
+ description,
+ pendingIntent
+ ).apply {
+ setEnabled(enabled)
+ }
+ }
+
+ private fun notifyFlutterPipAction(action: String) {
+ pipChannel?.invokeMethod("onAction", mapOf("action" to action))
+ }
+
+ private fun registerPipActionReceiverIfNeeded() {
+ if (pipActionReceiverRegistered || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
+ return
+ }
+ val filter = IntentFilter().apply {
+ addAction(actionPipPlayPause)
+ addAction(actionPipForward)
+ addAction(actionPipToggleDanmaku)
+ }
+ ContextCompat.registerReceiver(
+ this,
+ pipActionReceiver,
+ filter,
+ ContextCompat.RECEIVER_NOT_EXPORTED
+ )
+ pipActionReceiverRegistered = true
+ }
+
+ private fun unregisterPipActionReceiverIfNeeded() {
+ if (!pipActionReceiverRegistered) {
+ return
+ }
+ unregisterReceiver(pipActionReceiver)
+ pipActionReceiverRegistered = false
+ }
+
private fun getAvailableStorage(path: String): Long {
return try {
val stat = StatFs(path)
diff --git a/android/app/src/main/res/drawable/ic_pip_danmaku_off.xml b/android/app/src/main/res/drawable/ic_pip_danmaku_off.xml
new file mode 100644
index 00000000..74ba13fb
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_pip_danmaku_off.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:fillType="evenOdd"
+ android:pathData="m8.085 4.891-.999-1.499a1.008 1.008 0 0 1 1.679-1.118l1.709 2.566c.54-.008 1.045-.012 1.515-.012h.13c.345 0 .707.003 1.088.007l1.862-2.59a1.008 1.008 0 0 1 1.637 1.177l-1.049 1.46c.788.02 1.631.046 2.53.078 1.958.069 3.468 1.6 3.74 3.507.088.613.13 2.158.16 3.276l.001.027c.01.333.017.63.025.856a.987.987 0 0 1-1.974.069c-.008-.23-.016-.539-.025-.881v-.002c-.028-1.103-.066-2.541-.142-3.065-.143-1.004-.895-1.78-1.854-1.813a179.14 179.14 0 0 0-6.064-.131c-1.598 0-3.619.044-6.063.13a2.037 2.037 0 0 0-1.945 1.748c-.15 1.04-.225 2.341-.225 3.904 0 1.874.11 3.474.325 4.798.154.949.95 1.66 1.91 1.708a97.58 97.58 0 0 0 5.416.139.988.988 0 0 1 0 1.975 99.78 99.78 0 0 1-5.513-.141A4.012 4.012 0 0 1 2.197 17.7c-.236-1.446-.351-3.151-.351-5.116 0-1.64.08-3.035.245-4.184A4.013 4.013 0 0 1 5.92 4.96c.761-.027 1.483-.05 2.164-.069Zm4.436 4.707h-1.32v4.63h2.222v.848h-2.618v1.078h2.431a5.01 5.01 0 0 1 3.575-3.115V9.598h-1.276a8.59 8.59 0 0 0 .748-1.42l-1.089-.384a14.232 14.232 0 0 1-.814 1.804h-1.518l.693-.308a8.862 8.862 0 0 0-.814-1.408l-1.045.352c.297.396.572.847.825 1.364Zm-4.18 3.564.154-1.485h1.98V8.289h-3.2v.979h2.067v1.43H7.483l-.308 3.454h2.277c0 1.166-.044 1.925-.12 2.277-.078.352-.386.528-.936.528-.308 0-.616-.022-.902-.055l.297 1.067.062.004c.285.02.551.04.818.04 1.001-.066 1.562-.418 1.694-1.056.11-.638.176-1.903.176-3.795h-2.2Zm7.458.11v-.858h-1.254v.858H15.8Zm-2.376-.858v.858h-1.199v-.858h1.2Zm-1.199-.946h1.2v-.902h-1.2v.902Zm2.321 0v-.902H15.8v.902h-1.254Zm3.517 10.594a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm-.002-1.502a2.5 2.5 0 0 1-2.217-3.657l3.326 3.398a2.49 2.49 0 0 1-1.109.259Zm2.5-2.5c0 .42-.103.815-.286 1.162l-3.328-3.401a2.5 2.5 0 0 1 3.614 2.239Z" />
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_pip_danmaku_on.xml b/android/app/src/main/res/drawable/ic_pip_danmaku_on.xml
new file mode 100644
index 00000000..4106dd76
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_pip_danmaku_on.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:fillType="evenOdd"
+ android:pathData="M11.989 4.828c-.47 0-.975.004-1.515.012l-1.71-2.566a1.008 1.008 0 0 0-1.678 1.118l.999 1.5c-.681.018-1.403.04-2.164.068a4.013 4.013 0 0 0-3.83 3.44c-.165 1.15-.245 2.545-.245 4.185 0 1.965.115 3.67.35 5.116a4.012 4.012 0 0 0 3.763 3.363l.906.046c1.205.063 1.808.095 3.607.095a.988.988 0 0 0 0-1.975c-1.758 0-2.339-.03-3.501-.092l-.915-.047a2.037 2.037 0 0 1-1.91-1.708c-.216-1.324-.325-2.924-.325-4.798 0-1.563.076-2.864.225-3.904.14-.977.96-1.713 1.945-1.747 2.444-.087 4.465-.13 6.063-.131 1.598 0 3.62.044 6.064.13.96.034 1.71.81 1.855 1.814.075.524.113 1.962.141 3.065v.002c.01.342.017.65.025.88a.987.987 0 1 0 1.974-.068c-.008-.226-.016-.523-.025-.856v-.027c-.03-1.118-.073-2.663-.16-3.276-.273-1.906-1.783-3.438-3.74-3.507-.9-.032-1.743-.058-2.531-.078l1.05-1.46a1.008 1.008 0 0 0-1.638-1.177l-1.862 2.59c-.38-.004-.744-.007-1.088-.007h-.13Zm.521 4.775h-1.32v4.631h2.222v.847h-2.618v1.078h2.618l.003.678c.36.026.714.163 1.01.407h.11v-1.085h2.694v-1.078h-2.695v-.847H16.8v-4.63h-1.276a8.59 8.59 0 0 0 .748-1.42L15.183 7.8a14.232 14.232 0 0 1-.814 1.804h-1.518l.693-.308a8.862 8.862 0 0 0-.814-1.408l-1.045.352c.297.396.572.847.825 1.364Zm-4.18 3.564.154-1.485h1.98V8.294h-3.2v.98H9.33v1.43H7.472l-.308 3.453h2.277c0 1.166-.044 1.925-.12 2.277-.078.352-.386.528-.936.528-.308 0-.616-.022-.902-.055l.297 1.067.062.005c.285.02.551.04.818.04 1.001-.067 1.562-.419 1.694-1.057.11-.638.176-1.903.176-3.795h-2.2Zm7.458.11v-.858h-1.254v.858h1.254Zm-2.376-.858v.858h-1.199v-.858h1.2Zm-1.199-.946h1.2v-.902h-1.2v.902Zm2.321 0v-.902h1.254v.902h-1.254Z" />
+ <path
+ android:fillColor="#FF00AEEC"
+ android:fillType="evenOdd"
+ android:pathData="M22.846 14.627a1 1 0 0 0-1.412.075l-5.091 5.703-2.216-2.275-.097-.086-.008-.005a1 1 0 0 0-1.322 1.493l2.963 3.041.093.083.007.005a1 1 0 0 0 1.354-.124l5.81-6.505.08-.102.005-.008a1 1 0 0 0-.166-1.295Z" />
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_pip_forward_80.png b/android/app/src/main/res/drawable/ic_pip_forward_80.png
new file mode 100644
index 00000000..4d60a9e1
Binary files /dev/null and b/android/app/src/main/res/drawable/ic_pip_forward_80.png differ
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 5c77addc..f31fb77e 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -6,6 +6,7 @@ import 'package:kazumi/pages/player/smallest_player_item_panel.dart';
import 'package:kazumi/utils/constants.dart';
import 'package:kazumi/utils/logger.dart';
import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/pip_utils.dart';
import 'package:kazumi/utils/webdav.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
@@ -124,6 +125,8 @@ class _PlayerItemState extends State<PlayerItem>
double lastPlayerSpeed = 1.0;
int episodeNum = 0;
+ bool? _lastPipPlaying;
+ bool? _lastPipDanmakuEnabled;
late mobx.ReactionDisposer _fullscreenListener;
@@ -147,6 +150,58 @@ class _PlayerItemState extends State<PlayerItem>
} catch (_) {}
}
+ Future<void> _syncAndroidAutoEnterPIPSetting() async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ final bool autoEnterPIPEnabled = setting.get(
+ SettingBoxKey.androidAutoEnterPIP,
+ defaultValue: false,
+ );
+ try {
+ await PipUtils.setAndroidAutoEnterPIPEnabled(autoEnterPIPEnabled);
+ } catch (e) {
+ KazumiLogger().w(
+ 'PlayerItem: failed to sync android auto enter pip setting',
+ error: e,
+ );
+ }
+ }
+
+ Future<void> _syncAndroidPIPPlayerPageState(bool inPlayerPage) async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ try {
+ await PipUtils.setAndroidPIPInPlayerPage(inPlayerPage);
+ } catch (e) {
+ KazumiLogger().w(
+ 'PlayerItem: failed to sync android pip player page state',
+ error: e,
+ );
+ }
+ }
+
+ Future<void> _updateAndroidPIPActions({bool force = false}) async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ final bool playing = playerController.playing;
+ final bool danmakuEnabled = playerController.danmakuOn;
+ if (!force &&
+ _lastPipPlaying == playing &&
+ _lastPipDanmakuEnabled == danmakuEnabled) {
+ return;
+ }
+
+ _lastPipPlaying = playing;
+ _lastPipDanmakuEnabled = danmakuEnabled;
+ await PipUtils.updateAndroidPIPActions(
+ playing: playing,
+ danmakuEnabled: danmakuEnabled,
+ );
+ }
+
void _loadShortcuts() {
keyboardShortcuts = {};
defaultShortcuts.forEach((key, defaultValue) {
@@ -382,11 +437,13 @@ class _PlayerItemState extends State<PlayerItem>
playerController.danmakuOn = false;
});
setting.put(SettingBoxKey.danmakuEnabledByDefault, false);
+ unawaited(_updateAndroidPIPActions(force: true));
return;
}
// if false and empty, show dialog.
if (playerController.danDanmakus.isEmpty) {
showDanmakuSwitch();
+ unawaited(_updateAndroidPIPActions(force: true));
return;
}
// turn on danmaku.
@@ -394,6 +451,7 @@ class _PlayerItemState extends State<PlayerItem>
playerController.danmakuOn = true;
});
setting.put(SettingBoxKey.danmakuEnabledByDefault, true);
+ unawaited(_updateAndroidPIPActions(force: true));
}
Future<void> _uploadHistoryToWebDav() async {
@@ -744,6 +802,7 @@ class _PlayerItemState extends State<PlayerItem>
playerController.buffer = playerController.playerBuffer;
playerController.duration = playerController.playerDuration;
playerController.completed = playerController.playerCompleted;
+ unawaited(_updateAndroidPIPActions());
_syncAudioServiceState();
// 弹幕相关
if (playerController.currentPosition.inMicroseconds != 0 &&
@@ -1396,7 +1455,32 @@ class _PlayerItemState extends State<PlayerItem>
_handleFullscreenChange(context);
},
);
- // workaround for #214
+ if (Platform.isAndroid) {
+ PipUtils.initPipHandler(
+ onAction: (action) async {
+ if (!mounted) return;
+
+ switch (action) {
+ case 'play_pause':
+ playerController.playOrPause();
+ break;
+
+ case 'toggle_danmaku':
+ handleDanmaku();
+ break;
+
+ case 'forward':
+ await skipOP();
+ break;
+ }
+
+ await _updateAndroidPIPActions(force: true);
+ },
+ );
+ unawaited(_syncAndroidAutoEnterPIPSetting());
+ unawaited(_syncAndroidPIPPlayerPageState(true));
+ unawaited(_updateAndroidPIPActions(force: true));
+ }
WidgetsBinding.instance.addObserver(this);
animationController ??= AnimationController(
duration: const Duration(milliseconds: 300),
@@ -1460,6 +1544,10 @@ class _PlayerItemState extends State<PlayerItem>
animationController?.dispose();
animationController = null;
_disposePlayerMenu();
+ if (Platform.isAndroid) {
+ unawaited(_syncAndroidPIPPlayerPageState(false));
+ PipUtils.disposePipHandler();
+ }
// Reset player panel state
playerController.lockPanel = false;
playerController.showVideoController = true;
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index a40a915a..64bf70b1 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -1,9 +1,11 @@
+import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:kazumi/bean/widget/embedded_native_control_area.dart';
import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/pip_utils.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/pages/player/player_controller.dart';
@@ -1111,15 +1113,32 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
// 跳过
forwardIcon(),
- if (Utils.isDesktop() && !videoPageController.isFullscreen)
+ if ((Utils.isDesktop() && !videoPageController.isFullscreen) || Platform.isAndroid)
IconButton(
- onPressed: () {
- if (videoPageController.isPip) {
- Utils.exitDesktopPIPWindow();
- } else {
- Utils.enterDesktopPIPWindow();
+ onPressed: () async {
+ if (Utils.isDesktop()) {
+ if (videoPageController.isPip) {
+ await PipUtils.exitDesktopPIPWindow();
+ } else {
+ await PipUtils.enterDesktopPIPWindow();
+ }
+ videoPageController.isPip = !videoPageController.isPip;
+ return;
+ }
+ final bool supported =
+ await PipUtils.isAndroidPIPSupported();
+ if (!supported) {
+ KazumiDialog.showToast(message: '当前设备不支持画中画');
+ return;
+ }
+ await PipUtils.updateAndroidPIPActions(
+ playing: playerController.playing,
+ danmakuEnabled: playerController.danmakuOn,
+ );
+ final bool entered = await PipUtils.enterAndroidPIPWindow();
+ if (!entered) {
+ KazumiDialog.showToast(message: '进入画中画失败');
}
- videoPageController.isPip = !videoPageController.isPip;
},
tooltip: '画中画',
icon: const Icon(
diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dart
index f73bc1b5..684b9a3c 100644
--- a/lib/pages/player/smallest_player_item_panel.dart
+++ b/lib/pages/player/smallest_player_item_panel.dart
@@ -1,8 +1,10 @@
+import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/pip_utils.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/pages/player/player_controller.dart';
@@ -561,15 +563,31 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
),
// 跳过
forwardIcon(),
- if (Utils.isDesktop())
+ if (Utils.isDesktop() || Platform.isAndroid)
IconButton(
- onPressed: () {
- if (videoPageController.isPip) {
- Utils.exitDesktopPIPWindow();
- } else {
- Utils.enterDesktopPIPWindow();
+ onPressed: () async {
+ if (Utils.isDesktop()) {
+ if (videoPageController.isPip) {
+ await PipUtils.exitDesktopPIPWindow();
+ } else {
+ await PipUtils.enterDesktopPIPWindow();
+ }
+ videoPageController.isPip = !videoPageController.isPip;
+ return;
+ }
+ final bool supported = await PipUtils.isAndroidPIPSupported();
+ if (!supported) {
+ KazumiDialog.showToast(message: '当前设备不支持画中画');
+ return;
+ }
+ await PipUtils.updateAndroidPIPActions(
+ playing: playerController.playing,
+ danmakuEnabled: playerController.danmakuOn,
+ );
+ final bool entered = await PipUtils.enterAndroidPIPWindow();
+ if (!entered) {
+ KazumiDialog.showToast(message: '进入画中画失败');
}
- videoPageController.isPip = !videoPageController.isPip;
},
tooltip: '画中画',
icon: const Icon(Icons.picture_in_picture,
diff --git a/lib/pages/settings/player_settings.dart b/lib/pages/settings/player_settings.dart
index 8be3cc87..63d2732b 100644
--- a/lib/pages/settings/player_settings.dart
+++ b/lib/pages/settings/player_settings.dart
@@ -7,6 +7,8 @@ import 'package:hive_ce/hive.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/utils/constants.dart';
import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/pip_utils.dart';
import 'package:card_settings_ui/card_settings_ui.dart';
class PlayerSettingsPage extends StatefulWidget {
@@ -23,6 +25,7 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
late int defaultAspectRatioType;
late bool hAenable;
late bool androidEnableOpenSLES;
+ late bool androidAutoEnterPIP;
late bool lowMemoryMode;
late bool playResume;
late bool showPlayerError;
@@ -50,6 +53,8 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
hAenable = setting.get(SettingBoxKey.hAenable, defaultValue: true);
androidEnableOpenSLES =
setting.get(SettingBoxKey.androidEnableOpenSLES, defaultValue: true);
+ androidAutoEnterPIP =
+ setting.get(SettingBoxKey.androidAutoEnterPIP, defaultValue: false);
lowMemoryMode =
setting.get(SettingBoxKey.lowMemoryMode, defaultValue: false);
playResume = setting.get(SettingBoxKey.playResume, defaultValue: true);
@@ -280,6 +285,22 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
description: Text('当前视频播放完毕后自动播放下一集', style: TextStyle(fontFamily: fontFamily)),
initialValue: autoPlayNext,
),
+ if (Platform.isAndroid)
+ SettingsTile.switchTile(
+ onToggle: (value) async {
+ androidAutoEnterPIP = value ?? !androidAutoEnterPIP;
+ await setting.put(SettingBoxKey.androidAutoEnterPIP,
+ androidAutoEnterPIP);
+ await PipUtils.setAndroidAutoEnterPIPEnabled(
+ androidAutoEnterPIP);
+ setState(() {});
+ },
+ title: Text('自动进入画中画',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('切到后台时,自动进入画中画',
+ style: TextStyle(fontFamily: fontFamily)),
+ initialValue: androidAutoEnterPIP,
+ ),
SettingsTile.switchTile(
onToggle: (value) async {
forceAdBlocker = value ?? !forceAdBlocker;
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index 84956b29..21b41e2d 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -53,7 +53,7 @@ abstract class _VideoPageController with Store {
@observable
bool isCommentsAscending = false;
- /// 画中画状态
+ /// 桌面画中画状态,Android 画中画状态不需要单独维护,进入画中画后会直接切换到系统的全局播放器界面
@observable
bool isPip = false;
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index 73e8e298..0a838a4c 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -11,6 +11,7 @@ import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:hive_ce/hive.dart';
import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/utils/pip_utils.dart';
import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:screen_brightness_platform_interface/screen_brightness_platform_interface.dart';
@@ -320,8 +321,8 @@ class _VideoPageState extends State<VideoPage>
KazumiDialog.dismiss();
return;
}
- if (videoPageController.isPip) {
- Utils.exitDesktopPIPWindow();
+ if (videoPageController.isPip && Utils.isDesktop()) {
+ PipUtils.exitDesktopPIPWindow();
videoPageController.isPip = false;
return;
}
diff --git a/lib/utils/pip_utils.dart b/lib/utils/pip_utils.dart
new file mode 100644
index 00000000..30f5af0e
--- /dev/null
+++ b/lib/utils/pip_utils.dart
@@ -0,0 +1,134 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+import 'package:kazumi/utils/logger.dart';
+import 'package:kazumi/utils/utils.dart';
+import 'package:window_manager/window_manager.dart';
+
+class PipUtils {
+ static bool androidPIPInited = false;
+
+ static Future<bool> isAndroidPIPSupported() async {
+ if (!Platform.isAndroid) {
+ return false;
+ }
+ const pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ try {
+ final bool? supported =
+ await pipChannel.invokeMethod('isPictureInPictureSupported');
+ return supported ?? false;
+ } on PlatformException catch (e) {
+ KazumiLogger().e("Failed to check Android PIP support: '${e.message}'.");
+ return false;
+ }
+ }
+
+ static Future<bool> enterAndroidPIPWindow(
+ {int width = 16, int height = 9}) async {
+ if (!Platform.isAndroid) {
+ return false;
+ }
+ const pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ try {
+ final bool? entered =
+ await pipChannel.invokeMethod('enterPictureInPictureMode', {
+ 'width': width,
+ 'height': height,
+ });
+ return entered ?? false;
+ } on PlatformException catch (e) {
+ KazumiLogger().e("Failed to enter Android PIP mode: '${e.message}'.");
+ return false;
+ }
+ }
+
+ static Future<void> updateAndroidPIPActions({
+ required bool playing,
+ required bool danmakuEnabled,
+ }) async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ const pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ try {
+ await pipChannel.invokeMethod('updatePictureInPictureActions', {
+ 'playing': playing,
+ 'danmakuEnabled': danmakuEnabled,
+ });
+ } on PlatformException catch (e) {
+ KazumiLogger().e("Failed to update Android PIP actions: '${e.message}'.");
+ }
+ }
+
+ static Future<void> setAndroidAutoEnterPIPEnabled(bool enabled) async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ const pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ try {
+ await pipChannel.invokeMethod('setAndroidAutoEnterPIPEnabled', {
+ 'enabled': enabled,
+ });
+ } on PlatformException catch (e) {
+ KazumiLogger().e(
+ "Failed to set Android auto-enter PIP enabled state: '${e.message}'.");
+ }
+ }
+
+ static Future<void> setAndroidPIPInPlayerPage(bool inPlayerPage) async {
+ if (!Platform.isAndroid) {
+ return;
+ }
+ const pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ try {
+ await pipChannel.invokeMethod('setAndroidPIPInPlayerPage', {
+ 'inPlayerPage': inPlayerPage,
+ });
+ } on PlatformException catch (e) {
+ KazumiLogger().e("Failed to set Android PIP page state: '${e.message}'.");
+ }
+ }
+
+ // 进入桌面设备小窗模式
+ static Future<void> enterDesktopPIPWindow() async {
+ await windowManager.setAlwaysOnTop(true);
+ await windowManager.setSize(const Size(480, 270));
+ }
+
+ // 退出桌面设备小窗模式
+ static Future<void> exitDesktopPIPWindow() async {
+ bool isLowResolution = await Utils.isLowResolution();
+ await windowManager.setAlwaysOnTop(false);
+ await windowManager.setSize(
+ isLowResolution ? const Size(800, 600) : const Size(1280, 860));
+ await windowManager.center();
+ }
+
+ static void initPipHandler({
+ required Future<void> Function(String action) onAction,
+ }) {
+ const MethodChannel pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ if (androidPIPInited) return;
+ androidPIPInited = true;
+
+ pipChannel.setMethodCallHandler((call) async {
+ if (!Platform.isAndroid || call.method != 'onAction') {
+ return;
+ }
+
+ final args = call.arguments;
+ final String? action =
+ (args is Map) ? args['action'] as String? : null;
+
+ if (action != null) {
+ await onAction(action);
+ }
+ });
+ }
+
+ static void disposePipHandler() {
+ const MethodChannel pipChannel = MethodChannel('com.predidit.kazumi/pip');
+ pipChannel.setMethodCallHandler(null);
+ androidPIPInited = false;
+ }
+}
diff --git a/lib/utils/storage.dart b/lib/utils/storage.dart
index 87dd43e1..c62829b1 100644
--- a/lib/utils/storage.dart
+++ b/lib/utils/storage.dart
@@ -322,6 +322,7 @@ class SettingBoxKey {
syncPlayEndPoint = 'syncPlayEndPoint',
androidEnableOpenSLES = 'androidEnableOpenSLES',
androidVideoRenderer = 'androidVideoRenderer',
+ androidAutoEnterPIP = 'androidAutoEnterPIP',
defaultSuperResolutionType = 'defaultSuperResolutionType',
superResolutionWarn = 'superResolutionWarn',
playerDisableAnimations = 'playerDisableAnimations',
diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart
index a80fe38e..1fdd4773 100644
--- a/lib/utils/utils.dart
+++ b/lib/utils/utils.dart
@@ -629,21 +629,6 @@ class Utils {
return '秋';
}
- // 进入桌面设备小窗模式
- static Future<void> enterDesktopPIPWindow() async {
- await windowManager.setAlwaysOnTop(true);
- await windowManager.setSize(const Size(480, 270));
- }
-
- // 退出桌面设备小窗模式
- static Future<void> exitDesktopPIPWindow() async {
- bool isLowResolution = await Utils.isLowResolution();
- await windowManager.setAlwaysOnTop(false);
- await windowManager.setSize(
- isLowResolution ? const Size(800, 600) : const Size(1280, 860));
- await windowManager.center();
- }
-
static bool isSameSeason(DateTime d1, DateTime d2) {
return d1.year == d2.year && (d1.month - d2.month).abs() <= 2;
}
@@ -715,4 +700,4 @@ class Utils {
action?.call();
});
}
-}
+}
\ No newline at end of file