[Xamarin] Android 透過 DownloadManager 下載檔案

2015-11-30

透過系統內建的 DownloadManager 來下載檔案 ,這樣不但可以下載檔案,還可以透過系統內建就幫助做到續傳的效果,而寫APP 離開後系統依然會繼續下載,因為很方便,所以特地介紹一下
Screenshot_2015-11-30-11-37-53
C# Code :


using System;
using Android.App;
using Android.OS;
using Android.Util;
using Android.Widget;
using Java.IO;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;
 
namespace SampleDownloadManager
{
    [Activity(Label = "SampleDownloadManager", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
 
        private DownloadManager DownloadManager1;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
 
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
 
            // Get our button from the layout resource,
            // and attach an event to it
            Button btnDownload = FindViewById<Button>(Resource.Id.btnDownload);
 
            btnDownload.Click += delegate
            {
                try
                {
                    //Init DownloadManager
                    DownloadManager1 = (DownloadManager)GetSystemService(DownloadService);
 
                    //製作下載請求
                    DownloadManager.Request request =
                        new DownloadManager.Request(
                            Uri.Parse("http://s.nownews.com/media_crop/91002/hash/dd/49/dd49f467ebd588a31c56c1dfa7d49d06.jpg"));
 
                    //可以透過wifi and mobile
                    request.SetAllowedNetworkTypes(DownloadNetwork.Mobile | DownloadNetwork.Wifi);
 
                    request.SetAllowedOverRoaming(false);
                    request.SetTitle("資料下載中");
                    request.SetDescription("請不要中斷,等候下載");
 
                    //存檔的目錄 預設我將放置到系統預設的下載
                    var dirPath =
                        new File(
                            Environment.GetExternalStoragePublicDirectory(
                                Environment.DirectoryDownloads) + "/SampleX/");
 
                    if (!dirPath.Exists())
                        dirPath.Mkdirs();
 
                    //存檔的實體路徑
                    var uriTarget = Uri.FromFile(new File(dirPath.AbsolutePath + "/hebe.jpg"));
                    request.SetDestinationUri(uriTarget);
 
                    DownloadManager1.Enqueue(request);
                }
                catch (Exception ex)
                {
                    //Log Error
                    Log.Error("SampleDownloadManager", ex.Message + "," + ex.StackTrace);
                }
 
 
 
            };
        }
    }
}
 

很簡單的Code 筆記一下.


當麻許的超技八 2014 | Donma Hsu Design.