49

Xamarin Forms: Close applications programmatically

 2 years ago
source link: https://www.banditoth.hu/2021/07/15/xamarin-forms-close-applications-programmatically/?utm_campaign=xamarin-forms-close-applications-programmatically
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In some scenarios, we need to programmatically close our application. We can do it in our common code with Xamarin Forms too. Buuuuuut …….

Can we close an iOS application?

There is no API provided for gracefully terminating an iOS application.

In iOS, the user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion.

Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen.

Source: https://developer.apple.com/library/archive/qa/qa1561/_index.html

Close on Android from Forms code

There is one important place to implement closing apps from code: When you are handling back button presses by yourself.

Imagine, that you have a main screen, which is the root page. When a users presses the hardware back button you should display a confirmer, that says “Do you really want to close the application?”

If the user choose yes, you should make a call like this:

DependencyService.Get<IPlatformSpecificService>().CloseApplication();

The definition of the IPlatformSpecificService should be look like this:

public interface IPlatformSpecificService
{
void CloseApplication();
}

And the Android implementation of the IPlatformSpecificService should be something like:

using Plugin.CurrentActivity;
[assembly: Dependency(typeof(DeviceSpecificService))]
namespace AnAwesomeCompany.AGreatProduct.Droid.DependencyServices
{
public class PlatformSpecificService: IPlatformSpecificService
{
public void CloseApplication()
{
CrossCurrentActivity.Current.Activity.FinishAndRemoveTask();
}
}
}

Activity supports a lot of closing methods of the application. FinishAndRemoveTask will clear the app from the recents list too.

Take a look at official Android documentation at: https://developer.android.com/reference/android/app/Activity#finishAndRemoveTask()


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK