Flutter后台下载管理插件background_downloader的使用

Flutter后台下载管理插件background_downloader的使用

简介

background_downloader 是一个用于iOS、Android、MacOS、Windows和Linux平台的后台文件下载和上传插件。通过创建 DownloadTask 来定义文件来源、存储位置以及如何监控下载过程,然后调用 FileDownloader().download 并等待结果。该插件在iOS上使用URLSessions,在Android上使用DownloadWorker,因此任务可以在应用处于后台时继续完成。

使用示例

基本下载示例

// 定义下载任务(仅显示部分参数)
final task = DownloadTask(
  url: 'https://google.com/search',
  urlQueryParameters: {'q': 'pizza'},
  filename: 'results.html',
  headers: {'myHeader': 'value'},
  directory: 'my_sub_directory',
  updates: Updates.statusAndProgress, // 请求状态和进度更新
  requiresWiFi: true,
  retries: 5,
  allowPause: true,
  metaData: 'data for me'
);

// 启动下载,并等待结果。下载过程中显示进度和状态变化
final result = await FileDownloader().download(task,
    onProgress: (progress) => print('Progress: ${progress * 100}%'),
    onStatus: (status) => print('Status: $status')
);

// 根据结果采取行动
switch (result.status) {
  case TaskStatus.complete:
    print('Success!');
    break;
  case TaskStatus.canceled:
    print('Download was canceled');
    break;
  case TaskStatus.paused:
    print('Download was paused');
    break;
  default:
    print('Download not successful');
}

批量下载示例

final tasks = [task1, task2, task3]; // 一组下载任务

// 下载批量文件
final result = await FileDownloader().downloadBatch(tasks,
  batchProgressCallback: (succeeded, failed) =>
    print('Completed ${succeeded + failed} out of ${tasks.length}, $failed failed')
);

监听事件示例

// 注册监听器以处理 `TaskUpdate` 事件,通常在应用的 `initState()` 中:
FileDownloader().updates.listen((update) {
  switch (update) {
    case TaskStatusUpdate():
      // 处理 TaskStatusUpdate,例如:
      switch (update.status) {
        case TaskStatus.complete:
          print('Task ${update.task.taskId} success!');
          break;
        case TaskStatus.canceled:
          print('Download was canceled');
          break;
        case TaskStatus.paused:
          print('Download was paused');
          break;
        default:
          print('Download not successful');
      }
      break;

    case TaskProgressUpdate():
      // 处理 TaskProgressUpdate,例如:
      progressUpdateStream.add(update); // 传递给小部件以显示进度条
      break;
  }
});

// 接下来,启动后台下载任务,例如:
final successfullyEnqueued = await FileDownloader().enqueue(DownloadTask(
  url: 'https://google.com',
  filename: 'google.html',
  updates: Updates.statusAndProgress
));

通知配置示例

// 配置所有任务的通知
FileDownloader().configureNotification(
  running: TaskNotification('Downloading', 'file: {filename}'),
  complete: TaskNotification('Download finished', 'file: {filename}'),
  progressBar: true
);

// 所有下载现在将在下载时显示通知,完成后也会显示通知。
// {filename} 将被替换为任务的实际文件名。

初始化设置

Android

此包需要Kotlin 1.9.20或以上版本才能编译。对于现代Flutter项目,这应该添加到 /android/settings.gradle 文件中:

plugins {
    id "org.jetbrains.kotlin.android" version "1.9.20" apply false
}

对于旧的Flutter项目,Kotlin版本是在 android/build.gradle 文件中设置的:

buildScript {
    ext.kotlin_version = '1.9.20'
}

iOS

确保启用了Background Fetch功能:

  1. 在XCode中选择Runner target。
  2. 选择Signing & Capabilities选项卡。
  3. 点击+图标添加功能。
  4. 选择“Background Modes”。
  5. 勾选“Background Fetch”。

MacOS

需要请求特定权限以访问网络。打开 macos/Runner/DebugProfile.entitlementsmacos/Runner/Release.entitlements 文件并添加以下键值对:

<key>com.apple.security.network.client</key>
<true/>

更多功能

  • 任务跟踪数据库:可以通过激活跟踪来持久化记录任务状态和进度。
  • 权限管理:可以检查和请求用户权限,如显示通知、移动文件到共享存储等。
  • 任务管理:支持取消、暂停和恢复任务。
  • 多任务队列:可以配置并发任务的数量和优先级。
  • 认证和回调:提供原生回调以执行复杂的任务管理功能,如刷新令牌。

更多详细信息请参考官方文档和配置指南。

示例代码

完整示例代码可以在 GitHub 上找到,其中包含了一个完整的演示应用程序,展示了如何使用 background_downloader 插件进行文件下载和上传操作。


更多关于Flutter后台下载管理插件background_downloader的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter后台下载管理插件background_downloader的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用background_downloader插件来实现后台下载管理的示例代码。background_downloader是一个流行的Flutter插件,它允许应用在后台下载文件,同时保持应用的响应性和电池效率。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加background_downloader的依赖:

dependencies:
  flutter:
    sdk: flutter
  background_downloader: ^x.y.z  # 请使用最新版本号

然后运行flutter pub get来安装依赖。

步骤 2: 配置权限

由于下载文件通常涉及到访问设备的存储,你需要在AndroidManifest.xmlInfo.plist中添加必要的权限。

Android:

android/app/src/main/AndroidManifest.xml中添加:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

iOS:

ios/Runner/Info.plist中添加:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>NSAppleMusicUsageDescription</key>
<string>We need your permission to access music files.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need your permission to save photos.</string>

步骤 3: 实现下载逻辑

在你的Flutter项目中,创建一个服务或页面来管理下载。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:background_downloader/background_downloader.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DownloadPage(),
    );
  }
}

class DownloadPage extends StatefulWidget {
  @override
  _DownloadPageState createState() => _DownloadPageState();
}

class _DownloadPageState extends State<DownloadPage> {
  String downloadId = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Background Downloader Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _startDownload,
              child: Text('Start Download'),
            ),
            if (downloadId.isNotEmpty)
              Text("Download ID: $downloadId"),
          ],
        ),
      ),
    );
  }

  void _startDownload() async {
    String url = "https://example.com/yourfile.zip";
    String destination = "${(await getExternalStorageDirectory())!.path}/yourfile.zip";

    BackgroundDownloader.enqueue(
      configFile: DownloadConfig(
        id: newUuid(),
        url: url,
        savedDir: destination,
        headers: <String, String>{
          'Authorization': 'Bearer your_token', // 如果需要身份验证,请添加适当的头部
        },
      ),
    ).then((id) {
      setState(() {
        downloadId = id;
      });
      print("Download started with ID: $id");
    }).catchError((error) {
      print("Error starting download: $error");
    });
  }

  String newUuid() {
    return Uuid().v4(); // 使用uuid库生成唯一的下载ID
  }
}

注意

  1. 你需要添加uuid包来生成唯一的下载ID。在pubspec.yaml中添加:

    dependencies:
      uuid: ^x.y.z  # 请使用最新版本号
    
  2. getExternalStorageDirectory()函数来自path_provider包,如果你还没有添加它,请确保也添加这个依赖:

    dependencies:
      path_provider: ^x.y.z  # 请使用最新版本号
    

步骤 4: 监听下载状态

你可以使用BackgroundDownloader.status(downloadId)来检查下载的状态。例如,你可以在应用的某个地方(如InitState或定时器中)定期检查下载状态并更新UI。

@override
void initState() {
  super.initState();
  _checkDownloadStatus();
}

void _checkDownloadStatus() {
  if (downloadId.isNotEmpty) {
    BackgroundDownloader.status(downloadId).then((status) {
      print("Download status: $status");
      // 根据状态更新UI
    }).catchError((error) {
      print("Error checking download status: $error");
    });
  }

  // 使用定时器定期检查下载状态
  Timer.periodic(Duration(seconds: 5), (timer) {
    _checkDownloadStatus();
  });
}

结论

以上是一个基本的示例,展示了如何使用background_downloader插件在Flutter中实现后台下载管理。你可以根据具体需求扩展这个示例,比如添加更多的错误处理、进度更新、用户通知等。

回到顶部