dart 如何在Flutter中后台下载

7eumitmz  于 11个月前  发布在  Flutter
关注(0)|答案(1)|浏览(161)

我这个代码我使用后台服务和fourground servidce与这个包flutter_background_service:^2.4.6
和创建下载与dio和我想当我关闭progrqram下载仍然继续,但当我关闭它它写29):Flutter背景服务:2023-07-30 15:33:32.208773 V/后台服务(31829):服务已在运行,正在使用现有服务
但下载停止
我的代码

Future<void> initializeService() async {
final service = FlutterBackgroundService();

await service.configure(
androidConfiguration: AndroidConfiguration(
  // this will be executed when app is in foreground or background in separated isolate
  onStart: onStart,

  // auto start service
  autoStart: true,
  isForegroundMode: true,

  // notificationChannelId: 'my_foreground',
  // initialNotificationTitle: 'AWESOME SERVICE',
  // initialNotificationContent: 'Initializing',
  // foregroundServiceNotificationId: 888,
 ),
 iosConfiguration: IosConfiguration(
  // auto start service
  autoStart: true,

  // this will be executed when app is in foreground in separated isolate
  onForeground: onStart,

  // you have to enable background fetch capability on xcode project
  onBackground: onIosBackground,
 ),
 );

 // service.startService();
 }

 // to ensure this is executed
 // run app from xcode, then from xcode menu, select Simulate Background Fetch

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();

// SharedPreferences preferences = await SharedPreferences.getInstance();
// await preferences.reload();
// final log = preferences.getStringList('log') ?? <String>[];
// log.add(DateTime.now().toIso8601String());
// await preferences.setStringList('log', log);

return true;
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
// Only available for flutter 3.0.0 and later
DartPluginRegistrant.ensureInitialized();

// For flutter prior to version 3.0.0
// We have to register the plugin manually

SharedPreferences preferences = await SharedPreferences.getInstance();
 await preferences.setString("hello", "world");

/// OPTIONAL when use custom notification

if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
  service.setAsForegroundService();
 });

service.on('setAsBackground').listen((event) {
  service.setAsBackgroundService();
  });
  }

  service.on('stopService').listen((event) {
  service.stopSelf();
  });

  // bring to foreground
 Timer.periodic(const Duration(seconds: 1), (timer) async {
  if (service is AndroidServiceInstance) {
  if (await service.isForegroundService()) {
    /// OPTIONAL for use custom notification
    /// the notification id must be equals with AndroidConfiguration when you call configure()           method.
    service.setForegroundNotificationInfo(
        title: 'script academy', content: 'submychannel');
    // if you don't using custom notification, uncomment this
    // service.setForegroundNotificationInfo(
    //   title: "My App Service",
    //   content: "Updated at ${DateTime.now()}",
    // );
      }
     }

print('background service');
service.invoke('update');

/// you can see this log in logcat
print('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}');

// test using external plugin
final deviceInfo = DeviceInfoPlugin();
String? device;
if (Platform.isAndroid) {
  final androidInfo = await deviceInfo.androidInfo;
  device = androidInfo.model;
  }

 if (Platform.isIOS) {
  final iosInfo = await deviceInfo.iosInfo;
  device = iosInfo.model;
 }

 service.invoke(
  'update',
  {
    "current_date": DateTime.now().toIso8601String(),
    "device": device,
  },
);
 });
 }

class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);

@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
String text = "Stop Service";
double _downloadProgress = 0.0;
void downloadFile(String fileUrl) async {
Dio dio = Dio();

try {
  // Send an HTTP GET request to the file URL.
  final response = await dio.download(
         'https://5f8u2z8mn5qjqvfdxs59z5g6aw8djtnew24.kinguploadf2m15.xyz/Film/2022/The.Unbearable.Weight.of.Massive.Talent.2022.480p.WEB-DL.Farsi.Sub.Film2Media.mkv',
    '/storage/emulated/0/RPSApp/document/ali manafdfwer',
    options: Options(
      responseType: ResponseType.bytes,
      // followRedirects: false,
      // validateStatus: (status) => status! < 500,
      // receiveTimeout: 0,
    ),
    onReceiveProgress: (received, total) {
      if (total != -1) {
        setState(() {
          _downloadProgress = (received / total) * 100;
          print(_downloadProgress);
        });
        print('Download progress: $_downloadProgress%');
      }
    },
  );

  // Get the filename from the URL (you can also customize the filename).
  String fileName = fileUrl.split('/').last;

  // Get the platform-specific directory where the file will be saved.
  // In this example, we're using the downloads directory.
  String downloadsDirectory =
      '/storage/emulated/0/RPSApp/document/'; // Update this path for iOS or other platforms.

  // Create the file path where the downloaded file will be saved.
  String filePath = '$downloadsDirectory$fileName';

  // Write the file to the specified path.
  await File(filePath).writeAsBytes(response.data);

    print('File downloaded to: $filePath');
  } catch (error) {
     print('Error during download: $error');
   }
  }

  @override
 Widget build(BuildContext context) {
 return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: const Text('Service App'),
    ),
    body: Column(
      children: [
        ElevatedButton(
          child: const Text("Foreground Mode"),
          onPressed: () {
            FlutterBackgroundService().invoke("setAsForeground");
          },
        ),
        ElevatedButton(
          child: const Text("Background Mode"),
          onPressed: () {
            FlutterBackgroundService().invoke("setAsBackground");
          },
        ),
        ElevatedButton(
          child: Text(text),
          onPressed: () async {
            final service = FlutterBackgroundService();
            var isRunning = await service.isRunning();
            if (isRunning) {
              service.invoke("stopService");
            } else {
              service.startService();
            }

            if (!isRunning) {
              text = 'Stop Service';
            } else {
              text = 'Start Service';
            }
            setState(() {});
          },
        ),
        ElevatedButton(
          child: const Text("download Mode"),
          onPressed: () {
            String fileUrl =
                'https://example.com/sample.pdf'; // Replace this with your file URL.
            downloadFile(fileUrl);
          },
        ),
        Text('${_downloadProgress}'),
        const Expanded(
          child: LogView(),
        ),
      ],
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () {},
      child: const Icon(Icons.play_arrow),
     ),
    ),
    );
   }
   }

字符串
我尝试了我提供的代码中的后台和fourground服务,但它不起作用

相关问题