Microsoft MVP성태의 닷넷 이야기
Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager) [링크 복사], [링크+제목 복사],
조회: 8825
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13439정성태11/10/202311507닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/202310992닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/202311224닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/202311303닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/202310575닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/202310527스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20239384스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/202310181오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/202310733스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/202310928닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/202311055닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/202311204닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/202310715닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/202311221스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/202311089닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/202310989스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/202310742닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리 [1]
13421정성태10/4/202311010닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/202319246스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/202310842스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/202312475닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/202311768닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/202310367오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/202311799닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions) [2]
13414정성태9/16/202311142디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/202311954닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...