Xamarin.Essentials: アプリの操作

AppActions クラスを使用すると、アプリ アイコンからアプリのショートカットを作成して応答できます。

作業開始

この API の使用を始めるには、Xamarin.Essentials の概要ガイドを読み、ライブラリが正しくインストールされてプロジェクトに設定されていることを確認してください。

AppActions の機能にアクセスするには、次のプラットフォーム固有の設定が必要です。

インテント フィルターを MainActivity クラスに追加します。

[IntentFilter(
        new[] { Xamarin.Essentials.Platform.Intent.ActionAppAction },
        Categories = new[] { Android.Content.Intent.CategoryDefault })]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    ...

次に、次のロジックを追加して、アクションを処理します。

protected override void OnResume()
{
    base.OnResume();

    Xamarin.Essentials.Platform.OnResume(this);
}

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

    Xamarin.Essentials.Platform.OnNewIntent(intent);
}

アクションを作成する

クラスの Xamarin.Essentials への参照を追加します。

using Xamarin.Essentials;

アプリ アクションはいつでも作成可能ですが、多くの場合、アプリケーションの起動時に作成されます。 SetAsync メソッドを呼び出して、アプリのアクション一覧を作成します。

try
{
    await AppActions.SetAsync(
        new AppAction("app_info", "App Info", icon: "app_info_action_icon"),
        new AppAction("battery_info", "Battery Info"));
}
catch (FeatureNotSupportedException ex)
{
    Debug.WriteLine("App Actions not supported");
}

アプリ アクションが特定のバージョンのオペレーティング システムでサポートされていない場合は、FeatureNotSupportedException がスローされます。

AppAction には、次のプロパティを設定できます。

  • ID: アクションのタップに応答するために使用される一意の識別子。
  • タイトル: 表示する表示タイトル。
  • サブタイトル: タイトルの下に表示するサブタイトル (サポートされている場合)。
  • アイコン: 各プラットフォームで対応するリソース ディレクトリのアイコンと一致している必要があります。

App Actions on Homescreen

アクションへの応答

アプリケーションが起動するときに、OnAppAction イベントが登録されます。 アプリ アクションが選択されるときに、選択されたアクションに関する情報と共にイベントが送信されます。

public App()
{
    //...
    AppActions.OnAppAction += AppActions_OnAppAction;
}

void AppActions_OnAppAction(object sender, AppActionEventArgs e)
{
    // Don't handle events fired for old application instances
    // and cleanup the old instance's event handler
    if (Application.Current != this && Application.Current is App app)
    {
        AppActions.OnAppAction -= app.AppActions_OnAppAction;
        return;
    }
    MainThread.BeginInvokeOnMainThread(async () =>
    {
        await Shell.Current.GoToAsync($"//{e.AppAction.Id}");
    });
}

GetActions

AppActions.GetAsync() を呼び出すことによって、アプリ アクションの現在の一覧を取得できます。

API