在.NET MAUI应用中后台检测网络变化
背景: 我正在使用.NET MAUI开发一个Android应用。我的应用需要将文件传输到服务器。服务器可能只在局域网内可用,或者可通过互联网访问。在传输开始之前,会测试与服务器的连接。如果连接失败,传输将被推迟,直到有网络连接时再进行。当设备连接到不同的网络时,应该再次尝试连接。连接可以通过Wi‑Fi或蜂窝数据。
问题: 如何在应用处于后台时监听网络变化?我希望在网络变化时能够立即重新尝试传输,即使在此期间发生了手机重启。
解决方案
以下是一个DownloadService的粗略轮廓。 要完成它,需要:
- 在应用中只实例化一次,使其成为应用级别的单例服务
- 在应用中,考虑创建一个CancellationTokenSource(cts)
- 考虑添加SQLite,使BlockingCollection(阻塞集合)能持久化到SQLite数据库,并能在应用启动时恢复
- 因为我们是在小块(例如1K或 4K)进行下载,并使用取消标记,因此代码应当考虑网络变化
public static class DownloadService
{
static BlockingCollection<DownloadJob> downloadQueue = new();
public static void Download(string url, string localPath)
=> downloadQueue.Add(new DownloadJob { Url = url, LocalPath = localPath });
public static void StartProcessing(CancellationToken ct)
{
_ = Task.Run(() =>
{
while (!ct.IsCancellationRequested)
{
var job = downloadQueue.Take();
// insert code to download a chunk with
// 1. HttpClient
// 2. a Timeout
// 3. Using Range header and position offset
// 4. Append downloaded chunk to file
// 5. If download is completed, mark job as done and move continue to the next job
// 6. If download fails or is incomplete, re-add the job to the queue for retry
}
}, CancellationToken.None);
}
}
public class DownloadJob
{
public string Url { get; set; } = string.Empty;
public string LocalPath { get; set; } = string.Empty;
public int Position { get; set; } = 0;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。