The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(android): 后台保活防进程被回收
XiaoYouChR0d23f5cc9723
diff --git a/android/Dockerfile b/android/Dockerfileindex aaa1ff71..6ac481e6 100644--- a/android/Dockerfile+++ b/android/Dockerfile@@ -162,5 +162,14 @@ RUN DEPLOY_BZ=/usr/local/lib/python3.11/site-packages/PySide6/scripts/deploy_lib&& sed -i '/self.set_value("app", "title",/a\ self.set_value("app", "version", __import__("os").environ.get("GD3_VERSION", "") or "0.1")\n self.set_value("app", "android.accept_sdk_license", "True")\n self.set_value("buildozer", "log_level", "1")' "$DEPLOY_BZ" \&& grep -q 'GD3_VERSION' "$DEPLOY_BZ" && grep -q 'accept_sdk_license' "$DEPLOY_BZ" && grep -q 'log_level' "$DEPLOY_BZ" && echo "[patch] GD3_VERSION + accept_sdk_license + log_level=1 注入 OK"+# 后台保活(P2): KeepAliveService.java 烧进共用 bootstrap src(p4a 组 dist 连同 PythonService 编译);+# qt manifest 注册该 service(不带 android:process => 同进程托住主进程; dataSync)。改镜像 /opt/p4a 模板, 单列末层。+COPY keepalive_service/KeepAliveService.java /opt/p4a/pythonforandroid/bootstraps/common/build/src/main/java/org/ghostdownloader/KeepAliveService.java+RUN QTMAN=/opt/p4a/pythonforandroid/bootstraps/qt/build/templates/AndroidManifest.tmpl.xml \+ && sed -i '/<\/application>/i\ <service android:name="org.ghostdownloader.KeepAliveService" android:exported="false" android:foregroundServiceType="dataSync" />' "$QTMAN" \+ && grep -q 'KeepAliveService' "$QTMAN" \+ && chown -R builder:builder /opt/p4a/pythonforandroid/bootstraps/common/build/src/main/java/org/ghostdownloader \+ && echo "[patch] KeepAliveService 注入 OK"+USER builderWORKDIR /workdiff --git a/android/build_apk.sh b/android/build_apk.shindex 40fef9b4..d94a577e 100644--- a/android/build_apk.sh+++ b/android/build_apk.sh@@ -32,7 +32,7 @@ touch "$BUILD_MARKER"# jh2 有 recipe 交叉编译、gd3ffmpeg 走预置 jniLibs; 跳过 orjson(stdlib shim 兜)/desktop-notifier/uvloop 等。# deploy patch 把 GD3_EXTRA_REQ 追加到 requirements、GD3_EXTRA_PERM 到 permissions。export GD3_EXTRA_REQ="${GD3_EXTRA_REQ:-,pyjnius,niquests,urllib3-future,charset-normalizer,idna,h11,wassima,jh2,PySide6-Fluent-Widgets,PySideSix-Frameless-Window,darkdetect,loguru,qrcode,pypng,m3u8,mpegdash,aioftp,gd3ffmpeg}"-export GD3_EXTRA_PERM="${GD3_EXTRA_PERM:-,MANAGE_EXTERNAL_STORAGE}"+export GD3_EXTRA_PERM="${GD3_EXTRA_PERM:-,MANAGE_EXTERNAL_STORAGE,FOREGROUND_SERVICE,FOREGROUND_SERVICE_DATA_SYNC,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS}"# 启动器图标改指仓库 logo.png(deploy 默认 PySide6 python logo)export GD3_ICON="${GD3_ICON:-$REPO/app/assets/logo.png}"# adaptive icon(消 API26+ 白边)+ presplash(冷启动图), 资源由 make_launch_assets.py 从 logo.png 派生diff --git a/android/keepalive_service/KeepAliveService.java b/android/keepalive_service/KeepAliveService.javanew file mode 100644index 00000000..f3962c80--- /dev/null+++ b/android/keepalive_service/KeepAliveService.java@@ -0,0 +1,71 @@+package org.ghostdownloader;++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;++/**+ * 同进程前台服务:把宿主进程钉在前台优先级, 下载/浏览器服务切后台不被回收。+ * 不声明 android:process(与 Activity 同进程); 文案经 Intent extra "text" 传入; 起停由 Python 侧控制(见 android_keepalive.py)。+ */+public class KeepAliveService extends Service {+ private static final String CHANNEL_ID = "gd3_keepalive";+ private static final int NOTIFICATION_ID = 0x47443301;++ @Override+ public IBinder onBind(Intent intent) {+ return null;+ }++ @Override+ public int onStartCommand(Intent intent, int flags, int startId) {+ String text = (intent != null) ? intent.getStringExtra("text") : null;+ if (text == null) {+ text = "正在后台运行";+ }+ Notification notification = buildNotification(text);+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);+ } else {+ startForeground(NOTIFICATION_ID, notification);+ }+ // 进程若被杀,无 Python 引擎单独重启服务无意义,故不黏;起停全由 app 主动控制。+ return START_NOT_STICKY;+ }++ private Notification buildNotification(String text) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);+ NotificationChannel channel = new NotificationChannel(+ CHANNEL_ID, "后台任务", NotificationManager.IMPORTANCE_LOW);+ manager.createNotificationChannel(channel);+ }++ Notification.Builder builder = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)+ ? new Notification.Builder(this, CHANNEL_ID)+ : new Notification.Builder(this);++ Intent launch = getPackageManager().getLaunchIntentForPackage(getPackageName());+ if (launch != null) {+ int pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT;+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {+ pendingFlags |= PendingIntent.FLAG_IMMUTABLE;+ }+ builder.setContentIntent(PendingIntent.getActivity(this, 0, launch, pendingFlags));+ }++ return builder+ .setSmallIcon(getApplicationInfo().icon)+ .setContentTitle("Ghost Downloader")+ .setContentText(text)+ .setOngoing(true)+ .build();+ }+}diff --git a/android/main.py b/android/main.pyindex 9f45229d..5b1e00d4 100644--- a/android/main.py+++ b/android/main.py@@ -115,6 +115,8 @@ application.installTranslator(translator)coreService.start()+from app.supports.android_keepalive import keepAlive, requestIgnoreBatteryOptimizations+mainWindow = MobileMainWindow()featureService.load(mainWindow)taskService.load()@@ -123,6 +125,24 @@ mainWindow.updateThemeColor()mainWindow.show()setupTouchScrolling(mainWindow)+requestIgnoreBatteryOptimizations() # 跳电池优化豁免, 逃 Doze 后台限制(已豁免则静默)+# 浏览器扩展服务开启即须保活(随时接受扩展连接), 与下载各占一个保活理由, 引用计数互不踩+cfg.enableBrowserExtension.valueChanged.connect(lambda enabled: keepAlive.setReason("browser", bool(enabled)))+keepAlive.setReason("browser", cfg.enableBrowserExtension.value)++# 保活/测速由每秒 globalSpeedChanged(主线程可靠)驱动; 不走 coreService 跨线程信号(asyncio→plain slot 投递不可靠)+from app.supports.signal_bus import signalBus+++def _onGlobalSpeedChanged(speed: int) -> None:+ downloading = bool(coreService.runningTasks)+ keepAlive.setWakeLock(downloading)+ keepAlive.setReason("download", downloading)+ keepAlive.updateSpeed(speed)+++signalBus.globalSpeedChanged.connect(_onGlobalSpeedChanged)+application.aboutToQuit.connect(coreService.stop)application.aboutToQuit.connect(taskService.flushNow)diff --git a/app/supports/android_keepalive.py b/app/supports/android_keepalive.pynew file mode 100644index 00000000..937761bc--- /dev/null+++ b/app/supports/android_keepalive.py@@ -0,0 +1,111 @@+"""Android 后台保活 —— 同进程前台服务把宿主进程钉在前台优先级, 切后台不被回收。须主线程调。"""++from app.supports.android_notification import postNotification++_SERVICE = "org.ghostdownloader.KeepAliveService"+_CHANNEL = "gd3_keepalive" # 须与 KeepAliveService.java 一致+_NOTIF_ID = 0x47443301 # 须与 KeepAliveService.java 一致+++class AndroidKeepAlive:+ """按理由引用计数: 任一理由("download"/"browser")在即起前台服务, 全清才停。"""++ def __init__(self):+ self._reasons: set[str] = set()+ self._running = False+ self._text = ""+ self._speed = 0+ self._wakeLock = None++ def setReason(self, reason: str, active: bool) -> None:+ if active:+ self._reasons.add(reason)+ else:+ self._reasons.discard(reason)+ self._apply()++ def setWakeLock(self, active: bool) -> None:+ from jnius import autoclass, cast++ if active:+ if self._wakeLock is not None:+ return+ Context = autoclass("android.content.Context")+ PowerManager = autoclass("android.os.PowerManager")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ powerManager = cast("android.os.PowerManager", activity.getSystemService(Context.POWER_SERVICE))+ self._wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GhostDownloader::Download")+ self._wakeLock.setReferenceCounted(False)+ self._wakeLock.acquire()+ elif self._wakeLock is not None:+ self._wakeLock.release()+ self._wakeLock = None++ def updateSpeed(self, speed: int) -> None:+ self._speed = speed+ if self._running:+ self._apply()++ def _statusText(self) -> str:+ if self._speed > 0:+ from app.supports.utils import toReadableSize++ return f"{toReadableSize(self._speed)}/s"+ if "download" in self._reasons:+ return "正在下载"+ return "浏览器扩展保持连接"++ def _apply(self) -> None:+ if self._reasons:+ text = self._statusText()+ if not self._running:+ self._start(text)+ self._running = True+ elif text != self._text: # notify 同 id 更新, 不重发服务(避 12+ 后台起 FGS 限制)+ postNotification(_CHANNEL, "后台任务", _NOTIF_ID, "Ghost Downloader", text,+ ongoing=True, lowImportance=True)+ self._text = text+ elif self._running:+ self._stop()+ self._running = False+ self._text = ""++ def _start(self, text: str) -> None:+ from jnius import autoclass++ Intent = autoclass("android.content.Intent")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ intent = Intent(activity, autoclass(_SERVICE))+ intent.putExtra("text", text)+ if autoclass("android.os.Build$VERSION").SDK_INT >= 26:+ activity.startForegroundService(intent) # 8.0+ 须 5s 内 startForeground+ else:+ activity.startService(intent)++ def _stop(self) -> None:+ from jnius import autoclass++ Intent = autoclass("android.content.Intent")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ activity.stopService(Intent(activity, autoclass(_SERVICE)))+++keepAlive = AndroidKeepAlive()+++def requestIgnoreBatteryOptimizations() -> None:+ from jnius import autoclass, cast++ if autoclass("android.os.Build$VERSION").SDK_INT < 23:+ return+ Context = autoclass("android.content.Context")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ powerManager = cast("android.os.PowerManager", activity.getSystemService(Context.POWER_SERVICE))+ if powerManager.isIgnoringBatteryOptimizations(activity.getPackageName()):+ return+ Settings = autoclass("android.provider.Settings")+ Uri = autoclass("android.net.Uri")+ Intent = autoclass("android.content.Intent")+ intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)+ intent.setData(Uri.parse("package:" + activity.getPackageName()))+ activity.startActivity(intent)diff --git a/app/supports/android_notification.py b/app/supports/android_notification.pynew file mode 100644index 00000000..e8c3f54b--- /dev/null+++ b/app/supports/android_notification.py@@ -0,0 +1,44 @@+"""Android 本地通知 —— NotificationManager 投递, 完成 toast 与常驻通知共用 postNotification。须主线程调。"""+++def _reopenAppIntent(activity):+ from jnius import autoclass++ Intent = autoclass("android.content.Intent")+ PendingIntent = autoclass("android.app.PendingIntent")+ PythonActivity = autoclass("org.kivy.android.PythonActivity")++ intent = Intent(activity, PythonActivity)+ intent.setAction(Intent.ACTION_MAIN)+ intent.addCategory(Intent.CATEGORY_LAUNCHER)+ intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)+ flags = PendingIntent.FLAG_UPDATE_CURRENT+ if autoclass("android.os.Build$VERSION").SDK_INT >= 23:+ flags |= PendingIntent.FLAG_IMMUTABLE # 31+ 必须显式可变性+ return PendingIntent.getActivity(activity, 0, intent, flags)+++def postNotification(channelId: str, channelName: str, notifId: int, title: str, text: str,+ *, ongoing: bool, lowImportance: bool) -> None:+ from jnius import autoclass, cast++ Context = autoclass("android.content.Context")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ manager = cast("android.app.NotificationManager", activity.getSystemService(Context.NOTIFICATION_SERVICE))++ if autoclass("android.os.Build$VERSION").SDK_INT >= 26:+ NotificationManager = autoclass("android.app.NotificationManager")+ NotificationChannel = autoclass("android.app.NotificationChannel")+ importance = NotificationManager.IMPORTANCE_LOW if lowImportance else NotificationManager.IMPORTANCE_DEFAULT+ manager.createNotificationChannel(NotificationChannel(channelId, channelName, importance))+ builder = autoclass("android.app.Notification$Builder")(activity, channelId)+ else:+ builder = autoclass("android.app.Notification$Builder")(activity)+ builder.setSmallIcon(activity.getApplicationInfo().icon) # 必填, 缺则不弹+ builder.setContentTitle(title)+ builder.setContentText(text)+ builder.setOngoing(ongoing)+ builder.setAutoCancel(not ongoing)+ builder.setOnlyAlertOnce(True) # 每秒刷, 只首次提醒+ builder.setContentIntent(_reopenAppIntent(activity))+ manager.notify(notifId, builder.build()) # 同 notifId 再投即更新