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