Microsoft MVP성태의 닷넷 이야기
Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법 [링크 복사], [링크+제목 복사],
조회: 8926
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법

가령, 안드로이드의 Youtube 앱에서 "Share" 버튼을 눌렀을 때 내가 만든 응용 프로그램이 목록에 나오고 싶을 경우가 있습니다.

android_share_0.png

이에 대해 찾아보면 그럴싸한 공식 문서가 나오는데요,

Learn / .NET / .NET MAUI - Share
; https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/data/share?tabs=android

아쉽게도 저건, 앱에서 공유된 자원을 접근하는 방법을 설명합니다. 즉 Share에서 내 앱을 리스팅하는 내용이 아닙니다. 그래도 다행인 건, 이와 관련해 검색해 보면 IntentFilter와, ActivityAttribute.Exported = true 설정을 하면 된다는 글이 나옵니다.

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

namespace MauiApp1.Platforms.Android;

[Activity(Exported = true)]
[IntentFilter(new[] { Intent.ActionSend }, 
    Categories = [Intent.CategoryDefault], DataMimeType = "text/plain")]
internal class UrlShareActivity : Activity
{
    protected override async void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        if (this.Intent?.Action == Intent.Action && Intent.Type == "text/plain")
        {
            var data = Intent?.ClipData?.GetItemAt(0);
            var text = data.Text; // 사용자가 공유한 URL
        }
    }
}

Activity를 상속했고 ActivityAttribute 특성을 지정했으니 아래의 문서에 나오듯이,

Android app manifest
; https://learn.microsoft.com/en-us/dotnet/maui/android/manifest

"\obj\Debug\net8.0-android\AndroidManifest.xml" 파일로 위의 UrlShareActivity 설정 하나가 (빌드 시) 자동으로 추가됩니다.

<activity android:exported="true" android:name="crc64e2862aff4a97f0b0.UrlShareActivity">
    <intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

따라서, 이후 안드로이드 폰에서 Share 버튼을 누르면 앱 목록에 우리가 만든 앱이 함께 뜨게 됩니다.




그런데, 여기서 문제가 있습니다. ^^ 저렇게 UrlShareActivity를 통해 들어오면 이제 화면에는 그냥 빈 UI만 보인다는 점입니다. 이렇게!

android_share_1.png

대개의 경우, URL을 공유 받으면 원래의 App 화면에서 그 대응을 하게 될 것입니다. 그래서 다음과 같이 이동을 하고 싶을 텐데요,

await Shell.Current.GoToAsync("//MainPage");

동작을 하지 않습니다. ^^; 그러니까, 바로 이 문제를 지난번에 다룬 것입니다.

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

따라서 1) Intent 전환을 통해 MainActivity로 넘어오거나, 2) UrlShareActivity에서 안드로이드 axml UI 방식을 따라 제어를 하거나, 3) 아니면 애당초 MainActivity 자체를 Exported 대상으로 설정하는 방법을 택해야 합니다. 이번 글에서는, 1번 방법인 MainActivity로 전환하는 것을 가정하고 설명하겠습니다.

자, 그럼 Share 이후에 Intent 전환으로 (MainPage XAML을 소유한) MainActivity까지 뜨게 되었습니다. 이제 Share로 넘어온 정보를 MainActivity에서 취해야 하는데요, 이를 위해서는 UrlShareActivity 측에서 Intent를 넘길 때부터 공유 받은 그 정보를 먼저 넘겨야 합니다.

[Activity(Exported = true)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = [Intent.CategoryDefault], DataMimeType = "text/plain")]
internal class UrlShareActivity : Activity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        if (this.Intent == null)
        {
            return;
        }

        Intent intent = this.Intent;

        if (intent.Action == Intent.ActionSend && intent.Type == "text/plain")
        {
            var data = intent.ClipData?.GetItemAt(0);
            var text = data?.Text;

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            var mainIntent = new Intent(this, typeof(MainActivity));
            mainIntent.SetAction(Intent.ActionSend);
            mainIntent.SetType(intent.Type);
            mainIntent.PutExtra("url", text);

            StartActivity(mainIntent);
        }
    }
}

그리고 저걸 넘겨받는 MainActivity는, 정상적인 동작을 위해서는 LaunchMode를 LaunchMode.SingleTask로 했을 것이므로 OnCreate 또는 OnNewIntent가 발생합니다. 즉, 한 번도 실행한 적이 없거나 아니면 이미 종료 상태로 바뀌었다면 OnCreate가 발생하겠지만, 아직 이전 실행 상태가 지속 중이라면 OnNewIntent가 발생합니다.

따라서, MainActivity에서는 다음과 같은 식의 코드로 URL을 넘겨받을 수 있습니다.

// ...[생략]...
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        OnShare(this.Intent);
    }

    protected override void OnNewIntent(Intent? intent)
    {
        base.OnNewIntent(intent);
        OnShare(intent);
    }

    void OnShare(Intent? intent)
    {
        if (intent == null)
        {
            return;
        }

        if (intent.Action == Intent.ActionSend && intent.Type == "text/plain")
        {
            var text = intent.GetStringExtra("url");

            if (string.IsNullOrEmpty(text))
            {
                return;
            }
        }
    }

     // ...[생략]...
}

일단, 여기까지는 Android 플랫폼의 특성에 따른 Share 문제를 해결합니다.




자, 이제 남은 문제는, 저렇게 구한 text 정보를 어떻게 (.NET MAUI의 다중 플랫폼 환경인) MainPage로 넘기느냐입니다. 이것도 결국 Activity에서 Shell.Current.GoToAsync와 같은 메서드가 실행되지 않는 문제와 유사합니다. 즉, UI Page에 공식적으로 정보를 전달할 방법이 없습니다.

사실 개인적으로, Activity에서 UI Page를 연동할 방법이 없다는 것이 좀 이해가 안 됩니다. (MAUI 생초보자인 제가 모르는 걸 수도 있습니다. 혹시, 방법을 알고 계신 분은 덧글 부탁드립니다. ^^) 아마도 XAML 환경은 다중 플랫폼을 고려한 것이기 때문에 플랫폼 의존적인 부분과의 연동을 감춘 것이 아닌가... 라고 예상만 할 뿐입니다.

암튼, 이렇게 된 이상 (In 또는) Inter Process Communication을 쓰거나 기타 어떤 식으로든 정보를 전달할 수단을 찾아야 합니다. 그나마 가장 편한 것이, CommunityToolkit.Mvvm에 있는 Messenger가 아닐까 싶은데요,

.NET Maui pass data from MainActivity.cs to a view model in order to display it
; https://stackoverflow.com/questions/77346428/net-maui-pass-data-from-mainactivity-cs-to-a-view-model-in-order-to-display-it

Messaging Made Easy: A Guide to WeakReferenceMessenger in .NET MAUI
; https://cedricgabrang.medium.com/messaging-made-easy-a-guide-to-weakreferencemessenger-in-net-maui-dc0d131163c

그래서 우선 패키지 참조를 추가하고,

Install-Package CommunityToolkit.Mvvm

MainPage에서는 메시지 구독을 하고,

// ...[생략]...
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        WeakReferenceMessenger.Default.Register<UrlShareMessage>(this, (r, m) =>
        {
            var urlText = m.Value;
            this.Title = urlText; // Title에 공유 받은 텍스트를 설정
        });
    }

    // ...[생략]...
}

public class UrlShareMessage : ValueChangedMessage<string>
{
    public UrlShareMessage(string value) : base(value)
    {
    }
}

MainActivity에서는 메시지 발생을 하면 됩니다.

// ...[생략]...
public class MainActivity : MauiAppCompatActivity
{
    // ...[생략]...

    void OnShare(Intent? intent)(Intent? intent)
    {
        if (intent == null)
        {
            return;
        }

        if (intent.Action == Intent.ActionSend && intent.Type == "text/plain")
        {
            var text = intent.GetStringExtra("url");
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            WeakReferenceMessenger.Default.Send(new UrlShareMessage(text));
        }
    }
}

자, 이제 Youtube를 실행하고 "Share" 버튼을 눌러 URL을 공유하면 정상적으로 우리가 만든 App의 Title이 바뀌는 것을 볼 수 있습니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/11/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)
13743정성태9/26/20246411닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
13742정성태9/26/20246701닷넷: 2297. C# - ssh-keygen으로 생성한 ecdsa 유형의 Public Key 파일 해석 [1]파일 다운로드1
13741정성태9/25/20245882디버깅 기술: 202. windbg - ASP.NET MVC Web Application (.NET Framework) 응용 프로그램의 덤프 분석 시 요령
13740정성태9/24/20245741기타: 86. RSA 공개키 등의 modulus 값에 0x00 선행 바이트가 있는 이유(ASN.1 인코딩)
13739정성태9/24/20245886닷넷: 2297. C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성 [1]파일 다운로드1
13738정성태9/22/20245613C/C++: 174. C/C++ - 윈도우 운영체제에서의 file descriptor, FILE*파일 다운로드1
13737정성태9/21/20245973개발 환경 구성: 727. Visual C++ - 리눅스 프로젝트를 위한 빌드 서버의 msbuild 구성
13736정성태9/20/20245972오류 유형: 923. Visual Studio Code - Could not establish connection to "...": Port forwarding is disabled.
13735정성태9/20/20246047개발 환경 구성: 726. ARM 플랫폼용 Visual C++ 리눅스 프로젝트 빌드
13734정성태9/19/20245750개발 환경 구성: 725. ssh를 이용한 원격 docker 서비스 사용
13733정성태9/19/20246087VS.NET IDE: 194. Visual Studio - Cross Platform / "Authentication Type: Private Key"로 접속하는 방법
13732정성태9/17/20246122개발 환경 구성: 724. ARM + docker 환경에서 .NET 8 설치
13731정성태9/15/20246711개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [1]파일 다운로드2
13730정성태9/10/20246372오류 유형: 922. docker - RULE_APPEND failed (No such file or directory): rule in chain DOCKER
13729정성태9/9/20247120C/C++: 173. Windows / C++ - AllocConsole로 할당한 콘솔과 CRT 함수 연동 [1]파일 다운로드1
13728정성태9/7/20246931C/C++: 172. Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유파일 다운로드1
13727정성태9/6/20247469개발 환경 구성: 722. ARM 플랫폼 빌드를 위한 미니 PC(?) - Khadas VIM4 [1]
13726정성태9/5/20247383C/C++: 171. C/C++ - 윈도우 운영체제에서의 file descriptor와 HANDLE파일 다운로드1
13725정성태9/4/20246138디버깅 기술: 201. WinDbg - sos threads 명령어 실행 시 "Failed to request ThreadStore"
13724정성태9/3/20247998닷넷: 2296. Win32/C# - 자식 프로세스로 HANDLE 상속파일 다운로드1
13723정성태9/2/20248254C/C++: 170. Windows - STARTUPINFO의 cbReserved2, lpReserved2 멤버 사용자 정의파일 다운로드2
13722정성태9/2/20245990C/C++: 169. C/C++ - CRT(C Runtime) 함수에 의존성이 없는 프로젝트 생성
13721정성태8/30/20246023C/C++: 168. Visual C++ CRT(C Runtime DLL: msvcr...dll)에 대한 의존성 제거 - 두 번째 이야기
13720정성태8/29/20246189VS.NET IDE: 193. C# - Visual Studio의 자식 프로세스 디버깅
13719정성태8/28/20246332Linux: 79. C++ - pthread_mutexattr_destroy가 없다면 메모리 누수가 발생할까요?
13718정성태8/27/20247413오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...