Microsoft MVP성태의 닷넷 이야기
Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager) [링크 복사], [링크+제목 복사],
조회: 3699
글쓴 사람
정성태 (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)
13778정성태10/21/2024182C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/2024163Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/2024406C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/2024360개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/2024575Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/2024331Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/2024501Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
13771정성태10/17/2024709Linux: 88. WSL 2 리눅스 배포본 내에서의 pid 네임스페이스 구성
13770정성태10/17/2024573Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/2024591Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/2024613C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/2024595오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/2024692C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/2024761오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/2024714Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/2024757Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/2024799Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/2024734오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/2024748Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20241075C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/2024928오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/2024883닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/2024883오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20241059닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/2024924닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...