feat: running foreground service on mobile (#261)

This commit is contained in:
Levi authored and GitHub committed 2023-11-07 17:52:10 +08:00
1 parent 83838afce9
commit aae79c2449
11 files changed
+224 -153

No files matched your search

+1 -1
View File
@@ -47,7 +47,7 @@ android {
applicationId "com.gopeed" applicationId "com.gopeed"
// You can update the following values to match your application needs. // You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 19 minSdkVersion 21
targetSdkVersion 29 targetSdkVersion 29
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
versionName flutterVersionName versionName flutterVersionName
@@ -72,6 +72,12 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Add android:stopWithTask option only when necessary. -->
<service
android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
android:stopWithTask="true" />
<!-- Don't delete the meta-data below. <!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data <meta-data
+4 -3
View File
@@ -70,6 +70,7 @@
"extensionDevelop": "Develop Extensions", "extensionDevelop": "Develop Extensions",
"history": "History", "history": "History",
"clearHistory": "Clear History", "clearHistory": "Clear History",
"noHistoryFound": "No History Found" "noHistoryFound": "No History Found",
} "serviceTitle": "Download Service",
"serviceText": "Running"
}
+3 -1
View File
@@ -70,5 +70,7 @@
"extensionDevelop": "开发扩展", "extensionDevelop": "开发扩展",
"history": "历史记录", "history": "历史记录",
"clearHistory": "清空历史记录", "clearHistory": "清空历史记录",
"noHistoryFound": "暂无历史记录" "noHistoryFound": "暂无历史记录",
"serviceTitle": "下载服务",
"serviceText": "运行中"
} }
+9
View File
@@ -33,6 +33,15 @@ import Libgopeed
}) })
GeneratedPluginRegistrant.register(with: self) GeneratedPluginRegistrant.register(with: self)
SwiftFlutterForegroundTaskPlugin.setPluginRegistrantCallback(registerPlugins)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions) return super.application(application, didFinishLaunchingWithOptions: launchOptions)
} }
} }
func registerPlugins(registry: FlutterPluginRegistry) {
GeneratedPluginRegistrant.register(with: registry)
}
@@ -1 +1,2 @@
#import "GeneratedPluginRegistrant.h" #import "GeneratedPluginRegistrant.h"
#import <flutter_foreground_task/FlutterForegroundTaskPlugin.h>
@@ -4,6 +4,7 @@ import 'dart:ui';
import 'package:app_links/app_links.dart'; import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@@ -79,21 +80,18 @@ class AppController extends GetxController with WindowListener, TrayListener {
@override @override
void onReady() { void onReady() {
super.onReady(); super.onReady();
try {
_initDeepLinks(); _initDeepLinks().onError((error, stackTrace) =>
} catch (e) { logger.w("initDeepLinks error", error, stackTrace));
logger.w("initDeepLinks error", e);
} _initWindows().onError((error, stackTrace) =>
try { logger.w("initWindows error", error, stackTrace));
_initWindows();
} catch (e) { _initTray().onError(
logger.w("initWindows error", e); (error, stackTrace) => logger.w("initTray error", error, stackTrace));
}
try { _initForegroundTask().onError((error, stackTrace) =>
_initTray(); logger.w("initForegroundTask error", error, stackTrace));
} catch (e) {
logger.w("initTray error", e);
}
} }
@override @override
@@ -210,6 +208,42 @@ class AppController extends GetxController with WindowListener, TrayListener {
trayManager.addListener(this); trayManager.addListener(this);
} }
Future<void> _initForegroundTask() async {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'gopeed_service',
channelName: 'Gopeed Background Service',
channelImportance: NotificationChannelImportance.LOW,
showWhen: true,
priority: NotificationPriority.LOW,
iconData: const NotificationIconData(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
)),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
interval: 5000,
isOnceEvent: false,
autoRunOnBoot: true,
allowWakeLock: true,
allowWifiLock: true,
),
);
if (await FlutterForegroundTask.isRunningService) {
FlutterForegroundTask.restartService();
} else {
FlutterForegroundTask.startService(
notificationTitle: "serviceTitle".tr,
notificationText: "serviceText".tr,
);
}
}
Future<void> _toCreate(Uri uri) async { Future<void> _toCreate(Uri uri) async {
final path = uri.scheme == "magnet" final path = uri.scheme == "magnet"
? uri.toString() ? uri.toString()
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../../../routes/app_pages.dart'; import '../../../routes/app_pages.dart';
@@ -23,139 +24,141 @@ class HomeView extends GetView<HomeController> {
break; break;
} }
return Scaffold( return WithForegroundTask(
// extendBody: true, child: Scaffold(
body: Row( // extendBody: true,
// crossAxisAlignment: CrossAxisAlignment.start, body: Row(
children: [ // crossAxisAlignment: CrossAxisAlignment.start,
!ResponsiveBuilder.isNarrow(context) children: [
? NavigationRail( !ResponsiveBuilder.isNarrow(context)
extended: true, ? NavigationRail(
labelType: NavigationRailLabelType.none, extended: true,
minExtendedWidth: 170, labelType: NavigationRailLabelType.none,
groupAlignment: 0, minExtendedWidth: 170,
// useIndicator: false, groupAlignment: 0,
onDestinationSelected: (int index) { // useIndicator: false,
controller.currentIndex.value = index; onDestinationSelected: (int index) {
switch (index) { controller.currentIndex.value = index;
case 0: switch (index) {
delegate.offAndToNamed(Routes.TASK); case 0:
break; delegate.offAndToNamed(Routes.TASK);
case 1: break;
delegate.offAndToNamed(Routes.EXTENSION); case 1:
break; delegate.offAndToNamed(Routes.EXTENSION);
case 2: break;
delegate.offAndToNamed(Routes.SETTING); case 2:
break; delegate.offAndToNamed(Routes.SETTING);
} break;
}, }
destinations: [ },
NavigationRailDestination( destinations: [
icon: const Icon(Icons.task), NavigationRailDestination(
selectedIcon: const Icon(Icons.task), icon: const Icon(Icons.task),
label: Text('task'.tr), selectedIcon: const Icon(Icons.task),
), label: Text('task'.tr),
NavigationRailDestination( ),
icon: const Icon(Icons.extension), NavigationRailDestination(
selectedIcon: const Icon(Icons.extension), icon: const Icon(Icons.extension),
label: Text('extensions'.tr), selectedIcon: const Icon(Icons.extension),
), label: Text('extensions'.tr),
NavigationRailDestination( ),
icon: const Icon(Icons.settings), NavigationRailDestination(
selectedIcon: const Icon(Icons.settings), icon: const Icon(Icons.settings),
label: Text('setting'.tr), selectedIcon: const Icon(Icons.settings),
), label: Text('setting'.tr),
], ),
selectedIndex: controller.currentIndex.value, ],
leading: const Icon(Icons.menu), selectedIndex: controller.currentIndex.value,
// trailing: const Icon(Icons.info_outline), leading: const Icon(Icons.menu),
) // trailing: const Icon(Icons.info_outline),
: const SizedBox.shrink(), )
Expanded( : const SizedBox.shrink(),
child: GetRouterOutlet( Expanded(
initialRoute: Routes.TASK, child: GetRouterOutlet(
// anchorRoute: '/', initialRoute: Routes.TASK,
// filterPages: (afterAnchor) { // anchorRoute: '/',
// logger.w(afterAnchor); // filterPages: (afterAnchor) {
// logger.w(afterAnchor.take(1)); // logger.w(afterAnchor);
// return afterAnchor.take(1); // logger.w(afterAnchor.take(1));
// }, // return afterAnchor.take(1);
)) // },
]), ))
bottomNavigationBar: ResponsiveBuilder.isNarrow(context) ]),
? BottomNavigationBar( bottomNavigationBar: ResponsiveBuilder.isNarrow(context)
items: <BottomNavigationBarItem>[ ? BottomNavigationBar(
BottomNavigationBarItem( items: <BottomNavigationBarItem>[
icon: const Icon(Icons.task), BottomNavigationBarItem(
label: 'task'.tr, icon: const Icon(Icons.task),
), label: 'task'.tr,
BottomNavigationBarItem( ),
icon: const Icon(Icons.extension), BottomNavigationBarItem(
label: 'extensions'.tr, icon: const Icon(Icons.extension),
), label: 'extensions'.tr,
BottomNavigationBarItem( ),
icon: const Icon(Icons.settings), BottomNavigationBarItem(
label: 'setting'.tr, icon: const Icon(Icons.settings),
), label: 'setting'.tr,
], ),
currentIndex: controller.currentIndex.value, ],
// selectedItemColor: Get.theme.highlightColor, currentIndex: controller.currentIndex.value,
onTap: (index) { // selectedItemColor: Get.theme.highlightColor,
controller.currentIndex.value = index; onTap: (index) {
switch (index) { controller.currentIndex.value = index;
case 0: switch (index) {
delegate.offAndToNamed(Routes.TASK); case 0:
break; delegate.offAndToNamed(Routes.TASK);
case 1: break;
delegate.offAndToNamed(Routes.EXTENSION); case 1:
break; delegate.offAndToNamed(Routes.EXTENSION);
case 2: break;
delegate.offAndToNamed(Routes.SETTING); case 2:
break; delegate.offAndToNamed(Routes.SETTING);
} break;
}, }
) },
// StylishBottomBar( )
// option: AnimatedBarOptions( // StylishBottomBar(
// iconSize: 32, // option: AnimatedBarOptions(
// barAnimation: BarAnimation.blink, // iconSize: 32,
// iconStyle: IconStyle.Default, // barAnimation: BarAnimation.blink,
// opacity: 0.3, // iconStyle: IconStyle.Default,
// ), // opacity: 0.3,
// items: [ // ),
// BottomBarItem( // items: [
// icon: const Icon(Icons.file_download), // BottomBarItem(
// selectedColor: Get.theme.primaryColor, // icon: const Icon(Icons.file_download),
// title: Text('downloading'.tr)), // selectedColor: Get.theme.primaryColor,
// BottomBarItem( // title: Text('downloading'.tr)),
// icon: const Icon(Icons.done), // BottomBarItem(
// selectedColor: Get.theme.primaryColor, // icon: const Icon(Icons.done),
// title: Text('downloaded'.tr)), // selectedColor: Get.theme.primaryColor,
// BottomBarItem( // title: Text('downloaded'.tr)),
// icon: const Icon(Icons.settings), // BottomBarItem(
// selectedColor: Get.theme.primaryColor, // icon: const Icon(Icons.settings),
// title: Text('setting'.tr)), // selectedColor: Get.theme.primaryColor,
// ], // title: Text('setting'.tr)),
// // hasNotch: true, // ],
// currentIndex: controller.currentIndex.value, // // hasNotch: true,
// onTap: (index) { // currentIndex: controller.currentIndex.value,
// switch (index) { // onTap: (index) {
// case 0: // switch (index) {
// delegate.toNamed(Routes.DOWNLOADING); // case 0:
// controller.currentIndex.value = 0; // delegate.toNamed(Routes.DOWNLOADING);
// break; // controller.currentIndex.value = 0;
// case 1: // break;
// delegate.toNamed(Routes.DOWNLOADED); // case 1:
// controller.currentIndex.value = 1; // delegate.toNamed(Routes.DOWNLOADED);
// break; // controller.currentIndex.value = 1;
// case 2: // break;
// delegate.toNamed(Routes.SETTING); // case 2:
// controller.currentIndex.value = 2; // delegate.toNamed(Routes.SETTING);
// break; // controller.currentIndex.value = 2;
// } // break;
// }, // }
// ) // },
: const SizedBox.shrink(), // )
: const SizedBox.shrink(),
),
); );
}); });
} }
+6
View File
@@ -87,6 +87,8 @@ class LocaleKeys {
static const history = 'history'; static const history = 'history';
static const clearHistory = 'clearHistory'; static const clearHistory = 'clearHistory';
static const noHistoryFound = 'noHistoryFound'; static const noHistoryFound = 'noHistoryFound';
static const serviceTitle = 'serviceTitle';
static const serviceText = 'serviceText';
} }
class Locales { class Locales {
@@ -165,6 +167,8 @@ class Locales {
'history': 'History', 'history': 'History',
'clearHistory': 'Clear History', 'clearHistory': 'Clear History',
'noHistoryFound': 'No History Found', 'noHistoryFound': 'No History Found',
'serviceTitle': 'Download Service',
'serviceText': 'Running',
}; };
static const fa_IR = { static const fa_IR = {
'label': 'فارسی', 'label': 'فارسی',
@@ -434,6 +438,8 @@ class Locales {
'history': '历史记录', 'history': '历史记录',
'clearHistory': '清空历史记录', 'clearHistory': '清空历史记录',
'noHistoryFound': '暂无历史记录', 'noHistoryFound': '暂无历史记录',
'serviceTitle': '下载服务',
'serviceText': '运行中',
}; };
static const zh_TW = { static const zh_TW = {
'label': '中文 (正體) ', 'label': '中文 (正體) ',
+8
View File
@@ -310,6 +310,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
flutter_foreground_task:
dependency: "direct main"
description:
name: flutter_foreground_task
sha256: e48d2d810a2d643362e64de41146ed8e95d4dd282bae6abbb32309d9f0bf5d67
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.1.2"
flutter_form_builder: flutter_form_builder:
dependency: "direct main" dependency: "direct main"
description: description:
+1
View File
@@ -62,6 +62,7 @@ dependencies:
open_file: ^3.3.2 open_file: ^3.3.2
flutter_form_builder: ^9.1.1 flutter_form_builder: ^9.1.1
form_builder_validators: ^9.0.0 form_builder_validators: ^9.0.0
flutter_foreground_task: ^6.1.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter