Share via


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設定下列屬性:

  • 標識碼:用來響應動作點選的唯一標識碼。
  • 標題:要顯示的可見標題。
  • 子標題:如果支援子標題,則會顯示在標題底下。
  • 圖示:必須比對每個平台上對應資源目錄中的圖示。

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