Microsoft MVP성태의 닷넷 이야기
Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager) [링크 복사], [링크+제목 복사],
조회: 8819
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 4개 있습니다.)
Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법
; https://www.sysnet.pe.kr/2/0/13631

Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
; https://www.sysnet.pe.kr/2/0/13632

Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어
; https://www.sysnet.pe.kr/2/0/13634

Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
; https://www.sysnet.pe.kr/2/0/13640




C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)

MAUI 환경에서도 일반적인 HTTP 통신을 이용한 파일을 다운로드할 수 있습니다. 테스트를 간단하게 하기 위해 로컬에 ASP.NET Core 웹 서버를 구동하고, Android 에뮬레이터에서는 그 웹 서버로 (127.0.0.1이 아닌) "10.0.2.2" IP를 이용해 연결할 수 있습니다.

Connect to local web services from Android emulators and iOS simulators
; https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/local-web-services

그래서 대충 이런 식으로 코드를 만들 수 있습니다.

// https://www.sysnet.pe.kr/2/0/13631
string myPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// myPath == "/data/user/0/com.companyname.simpleplayer/files/Documents/"

if (Directory.Exists(myPath) == false)
{
    Directory.CreateDirectory(myPath);
}

string txtFilePath = Path.Combine(myPath, "test.txt");

using (HttpClient client = new HttpClient())
{
    string text = await client.GetStringAsync("http://10.0.2.2:15000/FileDownload");
    File.WriteAllText(txtFilePath, text);
}

위의 경우 (https가 아닌) http 통신을 시도하기 때문에 지난번 글에 설명한 것처럼,

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

이번에는 "localhost"가 아닌 "10.0.2.2" 항목을 network_security_config.xml 파일에 설정해 둬야 합니다.




간단한 통신이라면 저렇게 해도 문제가 없는데, 파일 다운로드가 시간이 걸리는 경우라면 HttpClient의 경우 이렇게 오류가 발생할 수 있습니다.

[ERROR] FATAL UNHANDLED EXCEPTION: System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.

물론 Timeout을 변경하면 되겠지만 Phone이라는 특성을 감안했을 때 다양한 통신 오류에 대한 대응을 해야 하는 귀찮음을 고려한다면 (안드로이드의 경우) 시스템 서비스로 제공하는 DownloadManager를 이용하는 것이 좋습니다. 이에 대해서는 아래의 글에서 이미 자세하게 다루고 있는데요,

Monitoring The Download Progress In Your App
; https://doumer.me/xamarin-android-download-manager-advanced-guide/

직접 실습을 해볼까요? ^^

그래도 나름 테스트이니, 다운로드를 길게 할 수 있는 환경이 있어야 하는데, 대용량 파일을 직접 다루는 것도 방법이겠지만 일부러 지연을 시키는 것도 나쁘진 않습니다. 따라서, ASP.NET Core 측의 Web API에 다음과 같은 식으로 Stream 코드를 만들면,

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers;

[ApiController]
[Route("[controller]")]
public class FileDownloadController : ControllerBase
{
    [HttpGet, HttpHead]
    public IActionResult Get()
    {
        if (HttpContext.Request.Method == "HEAD")
        {
            Response.Headers["Content-Length"] = "60";
            Response.Headers["Content-Type"] = "application/octet-stream";
            Response.Headers["Content-Disposition"] = "attachment; filename=\"test.txt\"";

            return Ok();
        }

        return File(new DelayStream(), "application/octet-stream", "test.txt");
    }
}

public class DelayStream : Stream
{
    public override bool CanRead => true;

    public override bool CanSeek => true;

    public override bool CanWrite => true;

    public override long Length => 60;

    long _position = 0;

    public override long Position { get => _position; set => _position = value; }

    public override void Flush() { }

    static byte[] _chunk = Encoding.UTF8.GetBytes("abcdefghij");

    public override int Read(byte[] buffer, int offset, int count)
    {
        int gap = (1000 * 60) / 6;
        Thread.Sleep(gap);

        int length = (int)Math.Min(Math.Max(0, Length - _position), _chunk.Length);
        Array.Copy(_chunk, 0, buffer, offset, length);

        _position += length;
        return length;
    }

    public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();

    public override void SetLength(long value) => throw new NotImplementedException();

    public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
}

대충 60바이트의 텍스트 파일을 1분에 걸쳐서 다운로드하게 됩니다.




자, 그럼 FileDownloadController.Get API를 안드로이드 측에서 DownloadManager를 이용해 이렇게 호출할 수 있습니다.

// DownloadManager Class
// https://learn.microsoft.com/en-us/dotnet/api/android.app.downloadmanager

private async void _btnDownload_Click(object? sender, EventArgs e)
{
    string downloadUrl = "http://10.0.2.2:15000/FileDownload";

    string fileName = await GetFileName(downloadUrl);
    if (string.IsNullOrEmpty(fileName))
    {
        return;
    }

    var manager = DownloadManager.FromContext(Android.App.Application.Context);
    var request = new DownloadManager.Request(Android.Net.Uri.Parse(downloadUrl));

    request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
    request.SetDestinationInExternalFilesDir(Platform.CurrentActivity,
        Android.OS.Environment.DirectoryDownloads, fileName);
    request.SetTitle("Title of Item");
    request.SetDescription("File Download");

    long downloadId = manager?.Enqueue(request) ?? 0;
    if (downloadId == 0)
    {
        return;
    }

    // ... [생략]... 원한다면 MonitorDownload(downloadId) 코드 구현;
}

// HEAD를 이용해 미리 파일명을 가져오고,
private async Task<string> GetFileName(string downloadUrl)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage? result = null;
            
        try
        { 
            result = await client.SendAsync(
                new HttpRequestMessage(HttpMethod.Head, downloadUrl));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return "";
        }

        result.Content.Headers.TryGetValues("Content-Disposition", out IEnumerable<string>? values);
        if (values != null)
        {
            string fileName = values.FirstOrDefault() ?? "";
            ContentDisposition contentDisposition = new ContentDisposition(fileName);
            return contentDisposition.FileName ?? "";
        }
    }

    return "";
}

그럼 약 10초 후에 아래의 경로에,

형식: /storage/emulated/0/Android/data/{app_id}/files/Download

예제: /storage/emulated/0/Android/data/com.companyname.simpleplayer/files/Download

test.txt 파일이 생성됩니다. 만약 이미 test.txt 파일이 해당 디렉터리에 존재한다면, DownloadManager는 test-1.txt, test-2.txt, ... 식으로 파일명을 변경해 저장합니다.




위의 예제 코드에서 DownloadManager.Enqueue 호출은 download ID를 반환하는 데 이를 이용해 다운로드 상태를 모니터링할 수 있습니다. 이에 대해서는 원문 Monitoring The Download Progress In Your App 글에서 MonitorDownload 메서드의 ComputeDownloadStatus 예제로 잘 보여주고 있습니다.

이와 함께 저작자는 ContentObservers 또는 ContentProviders 등을 이용한 방법도 Android에서 제공하고 있지만 (MAUI 이전 시절이었던) 그 당시의 Xamarin 환경에서는 동작시킬 수 없었다고 합니다. (아마도 지금의 MAUI 환경에서는 될지도 모릅니다. ^^)

어쨌든 그런 이유로, Device.StartTimer를 이용해 주기적으로 download ID에 해당하는 상태를 폴링 방식으로 계속 체크하는 코드를 공개했습니다.

private void MonitorDownload(long downloadId, int itemId)
{
    Device.StartTimer(TimeSpan.FromSeconds(1), () =>
    {
        try
        {
            var downloadMonitor = new DownloadMonitor();
            var downloadStatus = downloadMonitor.ComputeDownloadStatus(downloadId);

            return downloadStatus != DownloadStatus.Failed && downloadStatus != DownloadStatus.Successful;
        }
        catch (Exception e)
        {
            logger.LogError(e, $"Error computing download percentage for prodct id : {itemId}");
            return true;
        }
    });
}

internal class DownloadMonitor
{
    public DownloadStatus ComputeDownloadStatus(long downloadId)
    {
        long downloadedBytes = 0;
        long totalSize = 0;
        int status = 0;

        DownloadManager.Query query = new DownloadManager.Query();
        query.SetFilterById(downloadId);
        var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);

        var cursor = downloadManager.InvokeQuery(query);

        if (cursor != null && cursor.MoveToFirst())
        {
            String downloadFilePath =
                (cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri))).Replace("file://", "");
            var ids = AndroidUtilities.GetUserAnditemIdFromFilePath(downloadFilePath);

            try
            {
                downloadedBytes =
                    cursor.GetLong(cursor.GetColumnIndexOrThrow(DownloadManager.ColumnBytesDownloadedSoFar));
                totalSize =
                    cursor.GetInt(cursor.GetColumnIndexOrThrow(DownloadManager.ColumnTotalSizeBytes));
                status = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus));
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }

            var percentage = (new decimal(downloadedBytes) / new decimal(totalSize)) * 100;
            NotifyDownloadProgress(ids.itemId, (float)percentage);
        }

        return (DownloadStatus) status;
    }

    void NotifyDownloadProgress(int itemId, float percentage)
    {
        var args = new DownloadProgressEventArg()
        {
            itemId = itemId,
            Percentage = percentage
        };
        MessagingCenter.Instance.Send<object, DownloadProgressEventArg>(this, args.MessageName, args);
    }
}

만약 다운로드 파일의 진행 상태를 progress bar 등으로 표시하고 싶다면 저 코드를 이용하시면 됩니다. 반면, 다운로드 완료 결과만 받고 싶다면 (역시 원 저작자가 제공하는) 아래의 BroadcastReceiver 코드를 사용하시면 됩니다.

using Android.App;
using Android.Content;
using Android.OS;

namespace SimplePlayer.Platforms.Android;

[BroadcastReceiver(Enabled = true, Exported = true)]
[IntentFilter(new string[] { DownloadManager.ActionDownloadComplete })]
public class DownloadCompletedBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context? context, Intent? intent)
    {
        string action = intent?.Action ?? "";

        if (DownloadManager.ActionDownloadComplete.Equals(action) && intent?.Extras != null)
        {
            Bundle extras = intent.Extras;
            DownloadManager.Query q = new DownloadManager.Query();
            long downloadId = extras.GetLong(DownloadManager.ExtraDownloadId);
            q.SetFilterById(downloadId);
            var cursor = (context?.GetSystemService(Context.DownloadService) as DownloadManager)?.InvokeQuery(q);

            if (cursor != null && cursor.MoveToFirst())
            {
                int status = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus));

                string downloadFilePath = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri))?.Replace("file://", "") ?? "";
                string downloadTitle = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnTitle)) ?? "";

                if (status == (int)DownloadStatus.Successful)
                {
                    //Do what you want 
                }
                else if (status == (int)DownloadStatus.Failed)
                {
                    var code = cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnReason));
                    //Report download failure
                }

                cursor.Close();
            }
        }
    }
}

위의 코드 파일을 프로젝트의 ./Platforms/Android 디렉터리에 생성하고 빌드/실행하면, 이후 다운로드 완료 시 OnReceive 메서드가 호출되고, downloadFilePath 변수에 "/storage/emulated/0/Android/data/com.companyname.simpleplayer/files/Download/test.txt"와 같은 경로를 구할 수 있습니다.




그 외 몇 가지 더 언급하자면, DownloadManager는 해당 파일을 미리 대상 디렉터리에 생성하고 다운로드를 진행합니다. 따라서, 파일의 존재 여부로 다운로드 완료 여부를 판단하면 안 됩니다.

만약, 그런 경우를 고려해야 한다면 다운로드 시작 시점부터 디렉터리를 구분해서,

request.SetDestinationInExternalFilesDir(Platform.CurrentActivity, "downloading", streamFileName);

지정하고, 다운로드 완료 후에 원하는 디렉터리로 이동하는 동작을 해야 합니다.

// BroadcastReceiver.OnReceive

public override void OnReceive(Context? context, Intent? intent)
{
    // ... [생략]...

    if (status == (int)DownloadStatus.Successful)
    {
        // ... [생략]...

        string downloadFilePath = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri))?.Replace("file://", "") ?? "";

        string destinationPath = downloadFilePath.Replace("/downloading/", "/Download/");
        File.Move(downloadFilePath, destinationPath);
    }
}

또한, ICursor.GetString으로 구한 ColumnLocalUri 경로는 URL Encode 상태이므로 한글이 들어간 경우라면 URL Decode를 해야 합니다.

downloadFilePath = Uri.UnescapeDataString(downloadFilePath);

마지막으로, 안드로이드의 파일 시스템 자체는 여느 리눅스처럼 대소문자를 구분하지만, sdcard로 여겨지는 external storage, 즉 /storage/emulated/... 경로에 대해서는 FAT 파일 시스템을 따라 대소문자 구분을 하지 않는다고 합니다.

Isn't Android File.exists() case sensitive?
; https://stackoverflow.com/questions/6502712/isnt-android-file-exists-case-sensitive




자, 그럼 이제까지 설명한 내용을 종합해,

C# - MAUI에서 MediaElement 사용
; https://www.sysnet.pe.kr/2/0/13624

C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
; https://www.sysnet.pe.kr/2/0/13635

C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
; https://www.sysnet.pe.kr/2/0/13637

Youtube 앱에서 (공유 기능을 통해) 선택한 동영상을 DownloadManager를 이용해 다운로드한 후, MediaElement를 이용해 재생하는 앱을 어렵지 않게 만들 수 있습니다. ^^




어느 순간부터 안드로이드 에뮬레이터에서 DownloadManager.Enqueue 메서드를 호출했을 때 이런 오류가 발생한다면?

[JavaBinder] !!! FAILED BINDER TRANSACTION !!!  (parcel size = 2944)
[0:] Java.Lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
   at Java.Interop.JniEnvironment.InstanceMethods.CallLongMethod(JniObjectReference instance, JniMethodInfo method, JniArgumentValue* args) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/net7.0/JniEnvironment.g.cs:line 20245
   at Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualInt64Method(String encodedMember, IJavaPeerable self, JniArgumentValue* parameters) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:line 600
   at Android.App.DownloadManager.Enqueue(Request request) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net8.0/android-34/mcw/Android.App.DownloadManager.cs:line 1115
   at SimplePlayer.UrlShareActivity.<>c__DisplayClass5_0.<<_btnDownload_Click>b__0>d.MoveNext() in C:\temp\SimplePlayer\SimplePlayer\Platforms\Android\UrlShareActivity.cs:line 110
  --- End of managed Java.Lang.NullPointerException stack trace ---
...[생략]...

검색해 보면 이미 해당 다운로드가 시작된 상태인 경우 그럴 수 있다고 하는데, 다른 URL의 파일을 다운로드하려고 해도 동일한 오류가 발생합니다. 심지어 앱을 재시작해도 그렇고... 어쨌든, 이럴 때는 에뮬레이터를 재시작하면 됩니다. ^^;




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/10/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...
NoWriterDateCnt.TitleFile(s)
13591정성태4/2/20249422닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20249215Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20249602닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/202410655닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20249538오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/202412384Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/202410099Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/202411667개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법 [9]파일 다운로드1
13583정성태3/25/20249699Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/202410814Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/202410469개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20249460닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/202410410오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/202411145닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/202411072닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/202410344닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/202410801닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/202410281닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20249464닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20249466닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20249431닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/202410076닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/202410179닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20249716닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20249617오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20249542오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...