0

Closing app using following code

   Context CurrentContext = Android.App.Application.Context;

    public void CloseByFinish()
    {
        var activity = (Activity)CurrentContext;

        activity.FinishAffinity();

    }

getting specific cast invalid exception using xamarin 2.5

  • The easier way to close the app would just be Environment.Exit(0); then you don't really need to mess around with casts etc. you can use either the System, or Java assembly for your Environment call. – JoeTomks Jan 11 '18 at 08:54
  • Can you show some more code? – FreakyAli Jan 11 '18 at 09:59

1 Answers1

1

Specific Cast invalid exception for context to activity

You can't convert Android.App.Application.Context to Activity, as illustrated in the following diagram, they are the different type.

enter image description here

As David Wasser said ;

FinishAffinity() is not used to "close an application". It is used to remove a number of Activitys belonging to a specific application from the current task (which may contain Activitys belonging to multiple applications).

Even if you finish all of the Activitys in your application, the OS process hosting your app does not automatically go away (as it does when you call System.exit()). Android will eventually kill your process when it gets around to it. You have no control over this (and that is intentional).

Suggestion :

You could close your app by using the following code :

private void CloseApp()
{
    Java.Lang.JavaSystem.Exit(0);// Close this app process
    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}

Update :

If you use FinishAffinity in an Activity, modify your code like this :

public void CloseByFinish()
{
    this.FinishAffinity();
}
York Shen
  • 9,014
  • 1
  • 16
  • 40