Showing posts with label Xamarin. Show all posts

What to Choose in 2022, Native vs Hybrid vs Cross Platform? What is a Native App? Native apps are built specifically for a particular o...

Xamarin Development Interview Questions Xamarin Development Interview Questions

A blog about android developement

Xamarin

image_interview

What to Choose in 2022, Native vs Hybrid vs Cross Platform?


What is a Native App?

Native apps are built specifically for a particular operating system leveraging platform-specific programming languages.


What is a Hybrid App?

Hybrid app development is the combination of native and web solutions where developers need to embed the code written with the languages such as CSS, HTML, and JavaScript into a native app with the help of plugins including Ionic’s Capacitor, Apache Cordova, and so on which enables to get the access of native functionalities.


What is a Cross Platform App?

For the young entrepreneurs who assume cross-platform app development and hybrid app development are the same, let’s clear the dilemma in the first place.

Cross-platform vs hybrid app development, both have entirely different meanings from each other and play different roles. Cross-platform frameworks operate on the agenda to develop shareable and reusable code for building apps for different OS. Writing code once and reusing the same on multiple platforms helps in minimizing development costs and efforts.


What is Xamarin?

Xamarin is a cross-platform development tool that allows developers to create native iOS, Android, and Windows apps with a single codebase. Xamarin uses the C# programming language and the .NET framework, which makes it easy for developers who are already familiar with these technologies to get started with mobile app development.


How does the architecture of Xamarin work?

The Xamarin platform consists of two main components: the Xamarin SDK and the Xamarin Runtime. The Xamarin SDK contains all of the necessary tools and libraries for building iOS, Android, and Windows apps using the C# programming language. The Xamarin Runtime is a set of libraries that are required for running Xamarin apps on iOS, Android, and Windows devices.


How do you share code across different platforms using Xamarin?

One of the main benefits of using Xamarin is that it allows developers to share code across different platforms. This is possible because Xamarin uses a shared codebase, which means that developers can write code once and then reuse it on multiple platforms. This can save a lot of time and effort, as well as ensure that code is consistent across platforms.


What is the need for the Model-View-ViewModel (MVVM) pattern in Xamarin?

The Model-View-ViewModel can be used on all platforms. It intends to provide a clean separation between the user interface controls and their logic.

The separation of code in MVVM is divided into View, ViewModel, and Model:

  • View: the collection of visible elements, which also receives user input. This includes user interfaces (UI), animations, and text. The content of View is not interacted with directly to change what is presented.
  • ViewModel: located between the View and Model layers. This is where the controls for interacting with View are housed, while the binding is used to connect the UI elements in View to the controls in ViewModel.
  • Model: houses the logic for the program, which is retrieved by the ViewModel upon its own receipt of input from the user through View.


What is the HTTP client?

HTTP Client helps the developers to connect with the external world through the internet using REST-based services. HTTP Client class is used for sending HTTP requests and receiving HTTP responses from a resource, which is identified by URI. HTTP Client class present in System.Net.HTTP namespace. 


Xamarin.Forms Localization with .resx file

The built-in .NET localization framework can be used to build cross-platform multilingual applications with Xamarin.Forms.


Xamarin.Forms String and Image Localization

The built-in mechanism for localizing .NET applications uses RESX files and the classes in the System.Resources and System.Globalization namespaces. The RESX files containing translated strings are embedded in Xamarin.Forms assembly, along with a compiler-generated class that provides strongly-typed access to the translations. The translated text can then be retrieved in code.


Right-to-Left Localization

Flow direction is the direction in which the UI elements on the page are scanned by the eye. Right-to-left localization adds support for the right-to-left flow direction of Xamarin.Forms applications.


Dependency Service and how it works in Xamarin.Forms?

While developing apps with Xamarin.Forms, you will find that certain native platform-specific functionalities are not present in Xamarin.Forms API. This is because of the generic nature of Xamarin.Forms. Xamarin.Forms allow apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do. You need to necessarily define an interface and write platform-specific implementations of that interface in the platform project. The dependency service will find the correct implementation of that interface in the various platform projects. Xamarin.Forms apps need four components to use DependencyService.

Interface – The required functionality is defined by an interface in shared code. This needs to be implemented by each platform

Implementation Per Platform – The implementation of the above-mentioned interface for each platform.

Registration – To find the correct implementation of the interface for the suitable platform at runtime, it is required that each platform implementation class of the interface be registered with the DependencyService at runtime

Invoking Dependency Service- It is required that there be an explicit invocation of the Dependency service, which will then allow the Dependency service to choose the appropriate implementation based on the platform.


What is the App.cs class?

  • App.cs is the main class of the App which offers features like:
  • MainPage: It helps us to set the initial page of the App.
  • Properties Dictionary: It helps us to store the values across the state of the life cycle.
  • Static Current Property: It gives the instance of the current application object


Android Fragments

  • Android Fragment is part of the activity, it is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screens inside one activity.
  • Android fragment lifecycle is affected by the activity lifecycle because fragments are included in the activity.
  • Each fragment has its own life cycle methods that are affected by the activity life cycle because fragments are embedded in activity.
  • The FragmentManager class is responsible for making interactions between fragment objects.


What do you understand about RESTful Web Services?

RESTful web services are services that follow REST architecture. REST stands for Representational State Transfer and uses HTTP protocol (web protocol) for implementation. These services are lightweight, provide maintainability, scalability, and support communication among multiple applications that are developed using different programming languages. They provide means of accessing resources present at the server required for the client via the web browser by means of request headers, request body, response body, status codes, etc.


What is the lifecycle method of the Xamarin.Forms App?

Lifecycle methods are the set of techniques that are executed when the application enters a specific state. The ways are:

  • OnStart: This method will run when the application starts from the beginning.
  • OnSleep: This method will execute when the application goes into the background.
  • OnResume: This method will execute when the application comes in the foreground from the sleeping state.


What are the triggers? How many types of triggers are available?

Triggers allow us to declare actions in XAML, which changes the appearance of the control when a specific condition is met for a particular property of the control.

We can add triggers at the control level, page level, or application level in the resource dictionary. Here are the four types of triggers available. These are:

  • Property Trigger: This trigger executes when the property of the control set a particular value.
  • Data Trigger: This trigger is similar to a property trigger, but it uses data binding.
  • Event Trigger: This trigger occurs when an event occurs on the control.
  • Multi Trigger: This trigger allows us to set the conditions of multiple triggers before the action occurs.


What is Behaviour in Xamarin.Forms?

Behaviors let you add functionality to user interface controls without having to subclass them. Behaviors are written in code and added to controls in XAML or code. Behaviors are the best way to validate the user inputs such as email, phone number, etc.


What is data binding in Xamarin?

Data binding is a technique that is used to synchronize the source of the data with the user interface. When the data binding is done and the data or our business model changes, then it shows the changes automatically to the UI elements and vice versa.


What is IOC?

Inversion of Control (IOC) is a design principle (although, some people refer to it as a pattern). As the name suggests, it is used to invert different kinds of controls in object-oriented design to achieve loose coupling. Here, controls refer to any additional responsibilities a class has, other than its main responsibility. This includes control over the flow of an application and control over the flow of object creation or dependent object creation and binding.

IOC is all about inverting the control. To explain this in layman's terms, suppose you drive a car to your workplace. This means you control the car. The IOC principle suggests inverting the control, meaning that instead of driving the car yourself, you hire a cab, where another person will drive the car. Thus, this is called inversion of control - from you to the cab driver. You don't have to drive a car yourself and you can let the driver do the driving so that you can focus on your main work.


What is Dependency Injection?

Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.


Difference between MVC and MVVM Architecture (Tech Mahindra)

  • MVC architecture has one to many relationships between Controller & View.
  • MVVM architecture, one to many relationships between View & View Model.

MVC (Model View Controller)

MVVM (Model View ViewModel)

Controller is the entry point to the Application.

The view is the entry point to the Application.

One to many relationships between Controller & View.

One to many relationships between View & View Model.

View does not have reference to the Controller

View has references to the View-Model.

MVC is Old Model

MVVM is a relatively New Model.

Difficult to read, change, to unit test, and reuse this Model

The debugging process will be complicated when we have complex data bindings.

MVC Model component can be tested separately from the user

Easy for separate unit testing and code is event-driven.


How are Xamarin Forms different than Xamarin Android & Xamarin IOS?

Xamarin.Forms

Pros

  1. Create one UI for all platforms
  2. Use basic components that are available on all platforms (like Buttons, Text Fields, Spinners, etc.)
  3. No need to learn all the native UI frameworks
  4. Fast cross-platform development process
  5. Custom native renderers give you the ability to adjust the appearance and feel of controls

Cons

  1. It's still a new framework and still contains bugs
  2. Especially Windows RT is not yet stable
  3. It's sometimes slower than accessing the native controls directly
  4. Custom native renderers have boundaries and are poorly documented


Xamarin.Android, Xamarin.iOS, Windows Phone, Windows RT

Pros

  1. Create one UI per platform
  2. Easy ability to adjust the platform-specific UI features and components
  3. Get the maximum out of your UI

Cons

  1. The cross-platform development process is much slower
  2. You need to learn all native UI frameworks
  3. You may result in having duplicate code (as you describe almost the same UI in three different platform-specific ways)


What are custom renderers?

Custom renderers provide a powerful approach for customizing the appearance and behaviour of Xamarin. Forms controls. They can be used for small styling changes or sophisticated platform-specific layouts and behaviour customization.

Custom renderers allow the Generic Xamarin.Forms control to be customized in behaviour and look as per the platform they are going to be used on. This enables developers to give a native look and behaviour to the otherwise Generic Xamarin.Forms Control.

Xamarin Forms controls are NOT rendered directly on the native platform. Every Xamarin.Forms control has an accompanying renderer for each platform that creates an instance of a native control. The properties from the Xamarin Forms control are translated across to the native control, then the native control is placed in the native layout, which then gets rendered by the platform.

Custom Renderers allow developers to customize the appearance and/or behaviour of the control by writing their custom classes. Custom Renderers can be defined to have a custom behaviour or appearance for one platform while allowing the default behaviour on other platforms or they can be defined for each platform and provide customization for each different platform like iOS, Android, and the Universal Windows Platform (UWP). If instead of changing the complete behaviour and appearance only some trivial changes are required then 'Effects' can be used as an alternative.


What are the Effects and why should be used in Xamarin.Forms

5 Effects, like Custom Renderers, allow a developer to customize controls for a specific platform. Effects are preferred over Custom Renderers when small styling changes are required instead of a complete layout or behaviour change. Custom Effects are created for platform-specific projects by extending the base class PlatformEffect. Once created, they can be attached to the control it is meant for.

Effects don't have any type of related information about the control they are attached to and hence if they are specified with a wrong control they should gracefully degrade. Effects are reusable and can be parameterized to extend their reusability.

E.g. the sample application demonstrates a Focus Effect that changes the background colour of a control when it gains focus.


Xamarin.Forms MessagingCenter

MessagingCenter is one of the most important APIs that you should be aware of while working with Xamarin.Forms and MVVM. MessagingCenter includes a simple messaging service to send and receive messages.

There are APIs that are exposed by MessagingCenter:

Subscribe - Listens for messages with a certain signature and performs an action when they are received. (Multiple subscribers can be listening for the same message.)

Send - Publishes a message for listeners to enact upon. If no listeners have subscribed, then the message is ignored.


Push Notifications

  • Register your Application in the FireBase dashboard
  • Download the configuration file: Here you have to download the JSON file that will be later added to our project. (On Android this file is named google-services.json, and on iOS, it’s named GoogleService-Info.plist).


Push Notification events for iOS & Android

  • OnMessageReceived
  • OnNotificationReceived
  • OnNotificationOpened
  • OnTokenRefresh

https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=macos

https://www.telerik.com/blogs/how-to-use-push-notifications-xamarin-forms


What is XAML?

XAML allows developers to define user interfaces in Xamarin. Forms applications using markup rather than code. XAML is never required in Xamarin. Forms program, but it is often more succinct and more visually coherent than equivalent code, and potentially tool able.


.NET C# Interview Questions

What is delegate

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.


Important Points About Delegate

  • A delegate is a strongly typed function pointer (just like a pointer is there in C++ language).
  • A Delegate is a reference-type variable that holds the reference of a method.
  • We can call delegate-like methods in C#.
  • Delegates are used to raise the event in class and are associated with the event handler.
  • Delegates can be Non-Generic/ Generic.
  • public delegate int PerformCalculation(int x, int y);


Multicast Delegates

A useful property of delegate objects is that multiple objects can be assigned to one delegate instance by using the + operator. The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.

The - operator can be used to remove a component delegate from a multicast delegate.


What is Reflection

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


What is Partial class in c#

Partial Class is a unique feature of C#. It can break the functionality of a single class into many files. When the application is compiled, these files are then reassembled into a single class file. The partial keyword is used to build a partial class.


SOLID Principles In C#

SOLID principles are the design principles that enable us to manage most software design problems. Robert C. Martin compiled these principles in the 1990s. These principles provide us with ways to move from tightly coupled code and little encapsulation to the desired results of loosely coupled and encapsulated real needs of a business properly. SOLID is an acronym for the following.

 S: Single Responsibility Principle (SRP)

 O: Open-closed Principle (OCP)

 L: Liskov substitution Principle (LSP)

 I: Interface Segregation Principle (ISP)

 D: Dependency Inversion Principle (DIP)


What is an interface class? Give one example of it

An Interface is an abstract class that has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.


Boxing and Unboxing in C#

Boxing

Boxing is the process of converting a value type to the object type or any interface type implemented by this value type. Boxing is implicit.

int i = 10;

object o = i; //performs boxing


Unboxing

Unboxing is the reverse of boxing. It is the process of converting a reference type to a value type. Unboxing extracts the value from the reference type and assigns it to a value type. Unboxing is explicit. It means we have to cast explicitly.

object o = 10;

int i = (int)o; //performs unboxing


Difference between ObservableCollection and List.

An ObservableCollection can be updated from UI exactly like any ObservableCollection implements INotifyCollectionChanged which provides a notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated.

BindingList implements IBindingList.IBindingList provides notifications on collection changes, but not only that. It provides a whole bunch of functionality that can be used by the UI to provide a lot more things than only UI updates according to changes.


What is the difference between read-only and constants?

ReadOnly Keyword

Const Keyword

In C#, read-only fields can be created using readonly keyword

In C#, constant fields are created using const keyword.

ReadOnly is a runtime constant.

Const is a compile time constant.

The value of readonly field can be changed.

The value of the const field can not be changed.

It cannot be declared inside the method.

It can be declared inside the method.

In readonly fields, we can assign values in declaration and in the constructor part.

In const fields, we can only assign values in declaration part.

It can be used with static modifiers.

It cannot be used with static modifiers.


How to use nullable types in .Net?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.


Stack Vs Heap Memory - C#

In C#classes are always allocated on the heap. Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member

Category

Stack Memory

Heap Memory

What is Stack & Heap?

It is an array of memory.

It is a LIFO (Last In First Out) data structure.

In it data can be added to and deleted only from the top of it.

It is an area of memory where chunks are allocated to store certain kinds of data objects.

In it data can be stored and removed in any order.

How Memory is Manages?

 

 

Practical Scenario

 

Value of variable storing in stack

 

Value of variable storing in heap

What goes on Stack & Heap?

"Things" declared with the following list of type declarations are Value Types

(because they are from System.ValueType):

bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

"Things" declared with following list of type declarations are Reference Types

(and inherit from System.Object... except, of course, for object which is the System.Object object):

class, interface, delegate, object, string

Memory Allocation

Memory allocation is Static

Memory allocation is Dynamic

How is it Stored?

It is stored Directly

It is stored indirectly

Is Variable Resized?

Variables can’t be Resized

Variables can be Resized

Access Speed

Its access is fast

Its access is Slow

Visibility or Accessibility

It can be visible/accessible only to the Owner Thread

It can be visible/accessible to all the threads

Garbage Collector

 -

It is a special thread created by .NET runtime to monitor allocations of heap space.

It only collects heap memory since objects are only created in heap

What is the difference between “is” and “as” operators in c#?

An “is” operator can be used to check an object’s compatibility with respect to a given type, and the result is returned as a Boolean. An “as” operator can be used for casting an object to either a type or a class.

Difference between ref and out parameters

Ref

The ref keyword is used to pass an argument as a reference. This means that when the value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like the ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to the calling method.

What are sealed classes in C#?

We create sealed classes when we want to restrict the class to be inherited. The sealed modifier is used to prevent derivation from a class. If we forcefully specify a sealed class as a base class, then a compile-time error occurs.

C# - Indexers

An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can access the instance of this class using the array access operator ([ ]).

private int[] arr = new int[100];

public int s[int index] // indexer declaration
{

// The arr object will throw IndexOutOfRange exception.

get => arr[index];

set => arr[index] = value;

}

How to implement a singleton design pattern in C#?

The Singleton design pattern in C# is one of the most popular design patterns. In this pattern, a class has only one instance in the program that provides a global point of access to it. In other words, a singleton is a class that allows only a single instance of itself to be created and usually gives simple access to that instance.

There are various ways to implement a singleton pattern in C#. The following are the common characteristics of a singleton pattern.

 A private and parameterless single constructor

 Sealed class.

 Static variable to hold a reference to the single created instance

 A public and static way of getting the reference to the created instance.

Eg:

Public sealed class Singleton {

Private static readonly Singleton _instance = new Singleton();

}

Ascending and Descending Order Program (Tech Mahindra)

using System;

public class HelloWorld
{

public static void Main(string[] args)
{

int[] arr=new int[]{3,5,6,7,4};

int[] temparray=new int[3];

for(int i=array.Length-3,j=0;i<arr.Length;i++,j++)
{

temparray[j]=arr[i];

//Console.WriteLine(temparray[j]+" ");

}

Array.Sort(temparray);

Array.Reverse(temparray);

for (int i=0;i<temparray.Length;i++)
{

Console.WriteLine(temparray[i]+" ");

}

}

}

Write Out Palindrome Program in C#

using System;

public class HelloWorld
{

public static void Main(string[] args)
{

string name="madam";

char[] ReverseArray=name.ToCharArray();

Array.Reverse(ReverseArray);

string OriginalArray=new string(ReverseArray);

if(name==OriginalArray)

Console.WriteLine("Palindrome");

else

Console.WriteLine("Not Palindrome");

}

}

C# Program to print all permutations of a given string

using System;

class HelloWorld
{

static void Main()
{

string s;

string answer="";

Console.Write("Enter the string : ");

s = Console.ReadLine();

Console.Write("\nAll possible strings are : ");

permute(s, answer);

}

static void permute(String s, String answer)
{

if (s.Length == 0)
{

Console.Write(answer + " ");

return;

}

for(int i = 0 ;i < s.Length; i++)
{

char ch = s[i];

String left_substr = s.Substring(0, i);

String right_substr = s.Substring(i + 1);

String rest = left_substr + right_substr;

permute(rest, answer + ch);

}

}

}

Reference Link: https://www.codingninjas.com/codestudio/library/c-interview-questions-for-5-years-experience


Agile Methodology Development

Agile

Agile is a software development methodology to build software incrementally using short iterations of 1 to 4 weeks so that the development is aligned with the changing business needs.


Scrum

Scrum is a project management framework that enables a team to communicate and self-organize to make changes quickly, in accordance with Agile principles and that emphasizes teamwork, accountability, and iterative progress.


Scrum Master

A Scrum Master is a team leader and facilitator who helps team members to follow agile practices so that they can meet their commitments. The responsibilities of a scrum master are as follows

  1.  To enable close cooperation between all roles and functions.
  2.  To remove any blocks.
  3.  To shield the team from any disturbances.
  4.  To work with the organization to track the progress and processes of the company.
  5.  To ensure that Agile Inspect & Adapt processes are leveraged properly which includes
  6. Daily stand-ups,
  7. Planned meetings,
  8. Demo,
  9. Review,
  10. Retrospective Meetings, and
  11. To facilitate team meetings and decision-making process


Product Owner

A Product Owner is one who drives the product from a business perspective.

The responsibilities of a Product Owner are as follows

  • To define the requirements and prioritize their values.
  • To determine the release date and contents.
  • To take an active role in iteration planning and release planning meetings.
  • To ensure that, the team is working on the most valued requirement.
  • To represent the voice of the customer.
  • To accept the user stories that meet the definition of done and defined acceptance criteria.


What is a User Story?

  • A user story is a requirement that defines what is required by the user as functionality. A user story can be in two forms −
  • As a <User Role> I want <Functionality> so that <Business Value>
  • In order to <Business value> as a <User Role> I want <Functionality>


Agile - Manifesto

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change by following a plan

 

Introduction Xamarin.Essentials Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications. Andro...

Xamarin.Forms - Text To Speech Using Xamarin Essentials Xamarin.Forms - Text To Speech Using Xamarin Essentials

A blog about android developement

Xamarin

Introduction

Xamarin.Essentials

Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications. Android, iOS, and UWP offer unique operating system and platform APIs that developers have access to all in C# leveraging Xamarin. Xamarin.Essentials provides a single cross-platform API that works with any Xamarin.Forms, Android, iOS, or UWP application that can be accessed from shared code no matter how the user interface is created.

Text-to-Speech

This enables an application to utilize the built-in text-to-speech engines to speak back text from the device and also to query available languages that the engine can support.


Coding Part

Steps

  1. 1: Creating new Xamarin.Forms Projects
  2. 2: Implementation of Text to Speech 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: Implementation of Text to Speech in Xamarin Forms

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


Platform Specific Changes:

  • If your project's Target Android version is set to Android 11 (R API 30) you must update your Android Manifest with queries that are used with the new package visibility requirements.
  • Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node:

Xamarin Forms App Changes:

  • Add a reference to Xamarin.Essentials in your class:
  • Text-to-Speech works by calling the SpeakAsync method with text and optional parameters, and returns after the utterance has finished.
  • This API provide more options on how the audio is spoken back with SpeechOptions that allows setting the volume, pitch, and locale.

Full Code

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.

Introduction In this tutorial, we will learn how to create and use app shortcuts in the xamarin forms app using Xamar...

App Shortcuts in Xamarin Forms App Shortcuts in Xamarin Forms

A blog about android developement

Xamarin

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 to navigate to the corresponding page from the app icon.


Coding Part

Steps

  1. Step 1: Creating new Xamarin.Forms Projects
  2. Step 2: Setting up the App Actions in Android and iOS
  3. Step 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 in Android and iOS

    In this step, we will see how to setup 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 AppDelegate.cs MainActivity.cs MainPage.xaml.cs

    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.