App Shortcuts In Xamarin Forms

App Shortcuts in Xamarin Forms
 

Introduction

In this tutorial, we will learn how to create and use app shortcuts in the xamarin forms app using Xamarin Essentials - AppActions class lets you create and respond to app shortcuts from the app icon. This will allow navigating to the corresponding page from the app icon.

Coding Part - Steps

  1. Creating new Xamarin.Forms Projects
  2. Setting up the App Actions on Android and iOS
  3. Implementation of App Shortcuts in Xamarin Forms

Step 1: Creating new Xamarin.Forms Projects

Create New Project by selecting "New Project" - "Xamarin Cross Platform App" and Clicking "OK".

Note: Xamarin.Forms version should be greater than 5.0.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.


 

Step 2: Setting up the App Actions on Android and iOS

In this step, we will see how to set up the code for Android and iOS.

Android Setup

Add Intentfilter for App Action in your MainActivity.cs class. Refer to the below image.

Then add the following logic to handle actions:

iOS Setup

In the AppDelegate.cs add the following logic to handle actions:


 

Step 3: Implementation of App Shortcuts in Xamarin Forms

In this step, we will see how to implement the functionality in Xamarin.Forms.

Create App Actions in Xamarin.Forms

App Actions can be created at any time, but are often created when an application starts. Call the SetAsync method to create the list of actions for your app.

If App Actions are not supported on the specific version of the operating system a FeatureNotSupportedException will be thrown. The following properties can be set on an AppAction:

  1. Id: A unique identifier used to respond to the action tap.
  2. Title: The visible title to display.
  3. Subtitle: If supported a sub-title to display under the title.
  4. Icon: Must match icons in the corresponding resources directory on each platform.

When your application starts register for the OnAppAction event. When an app action is selected the event will be sent with information as to which action was selected.

Full Code

App.xaml.cs

using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamarinAppShortcuts
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            AppActions.OnAppAction += AppActions_OnAppAction;
            MainPage = new MainPage();
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
        void AppActions_OnAppAction(object sender, AppActionEventArgs e)
        {
            if (Current != this && Current is App app)
            {
                AppActions.OnAppAction -= app.AppActions_OnAppAction;
                return;
            }
            MainThread.BeginInvokeOnMainThread(async () =>
            {
                await Shell.Current.GoToAsync($"//{e.AppAction.Id}");
            });
        }
    }
}

AppDelegate.cs

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace XamarinAppShortcuts.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override void PerformActionForShortcutItem(UIApplication application, UIApplicationShortcutItem shortcutItem, UIOperationHandler completionHandler) 
            => Xamarin.Essentials.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler);
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

MainActivity.cs

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;

namespace XamarinAppShortcuts.Droid
{
    [Activity(Label = "App Shortcuts Sample", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    [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 OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        
        protected override void OnResume()
        {
            base.OnResume();
            Xamarin.Essentials.Platform.OnResume(this);
        }

        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            Xamarin.Essentials.Platform.OnNewIntent(intent);
        }
    }
}

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Essentials;
using System.Diagnostics;

namespace XamarinAppShortcuts
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void BtnAddShortcutClicked(object sender, EventArgs e)
        {
            try
            {
                await AppActions.SetAsync(
                    new AppAction("app_info", "App Info", icon: "info"),
                    new AppAction("app_notifications", "App Notifications", icon: "notification"));
            }
            catch (FeatureNotSupportedException ex)
            {
                Debug.WriteLine("App Actions not supported");
            }
        }
    }
}

Result

Download Code

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.


Similar Articles