🍇

.NET MAUI AndroidでActionSendのIntentを受け取る

に公開

いわゆる共有メニューからアプリケーションにテキストを渡す方法ですが、
微妙に調整が必要だったので、ここに書いておきます。

MainActivity.csでLaunchModeをシングルタスクに、
IntentFilterを追加します。

using Android.App;
using Android.Content;
using Android.Content.PM;


  [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true,
    LaunchMode = LaunchMode.SingleTask,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode |
    ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
  [IntentFilter([Intent.ActionSend],
    Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain")]

OnNewIntentを追加します。

  public class MainActivity : MauiAppCompatActivity
  {
    protected override void OnResume()
    {
      base.OnResume();
      Platform.OnResume(this);
    }

    protected override void OnNewIntent(Android.Content.Intent? intent)
    {
      base.OnNewIntent(intent);

      Platform.OnNewIntent(intent);

      if(intent != null) {
         if(intent.Action == Intent.ActionSend) {
          var data = intent.GetStringExtra(Intent.ExtraText);
          App.HandleText(data ?? string.Empty);
        }
      }
    }

  }

App.HandleTextを実装。これはこの方法でなくても良さそうですが…。

    /// <summary>
    /// テキスト付きで起動
    /// </summary>
    public static void HandleText(string text) {
      Current?.Dispatcher.Dispatch(async () => {
        if(Current.MainPage == null) {
          return;
        }

        await WritePageHandler.NewEditWithText(text);
      });
    }

Discussion