Microsoft MVP성태의 닷넷 이야기
Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager) [링크 복사], [링크+제목 복사],
조회: 8828
글쓴 사람
정성태 (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)
13237정성태1/30/202314269.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/202313036개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/202312502개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/202314903개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/202316115오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/202312016스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/202311236오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/202312003개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/202313870.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/202314416.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/202313322개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/202312293.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/202311619개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/202312122Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/202312056오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/202311897개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/202312103Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/202311730오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/202311380Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/202311249VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/202311971디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/202311889디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/202314909Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/202313774.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/202312159오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/202313542기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...