Microsoft MVP성태의 닷넷 이야기
Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager) [링크 복사], [링크+제목 복사],
조회: 8829
글쓴 사람
정성태 (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)
13262정성태2/15/202313458디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/202312945Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/202312189오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/202312137.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/202312888오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/202312303.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/202312443개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/202312651오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/202312542Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/202313688Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/202311578오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/202312170스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/202313748오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/202314354오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/202311025오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/202312591VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/202312426개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/202312962.NET Framework: 2093. C# - PKCS#8 PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/202312064VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/202313199디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/202312055디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/202310639디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/202311320디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/202310681디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/202314970.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/202314269.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...