0

I found some questions/answers on how to track when the app goes to the background, like this one: Run code when Android app is closed/sent to background

But I need to run the code only if the user actually closes the application.

To exemplify:

  1. The user clicks on the Overview button;
  2. The Android opens the list of thumbnail images of the recent apps;
  3. The user swipe the thumbnail of my app to remove it (here is where I need to run the code).

I tried to add some code to the OnDestroy() method, but it don't seem to be called when I do steps above. I know the code works because I've done a test where I call the Finish() right at the start of my OnCreate(), then the OnDestroy() is called and so my code.

I'm using Xamarin and MvvmCross, but Java code is welcome too.

Community
  • 1
  • 1

2 Answers2

1

Implement and register an instance of Android.Content.IComponentCallbacks2 and the listen for TrimMemory.UiHidden events:

LifecycleCallbacks:

public class LifecycleCallbacks : Java.Lang.Object, Android.Content.IComponentCallbacks2
{
    public void OnTrimMemory(TrimMemory level)
    {
        if (level == TrimMemory.UiHidden)
        {
            Console.WriteLine("Backgrounded...");
        }

    }

    public void OnConfigurationChanged(Configuration newConfig)
    {
    }

    public void OnLowMemory()
    {
    }
}

Registering an instance of LifecycleCallbacks:

[Activity (Label = "MyApp", MainLauncher = true)]
public class MainActivity : Activity
{
    protected override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);

        // ...

        Application.RegisterComponentCallbacks(new LifecycleCallbacks());

        // ...
    }
}
matthewrdev
  • 11,930
  • 5
  • 52
  • 64
0

Native android developer here, I'm not sure if Xamarin extends the native framework somehow making this possible, but natively it's currently not supported.

The OS does not necessarily call activities' onDestroy method when the app is killed, but when the Activity is killed. It's really different because the App can be killed without calling activities' onDestroy and the onDestroy can be called without the Application being killed.

I recommend looking up to Services and the Alarm Manager to actually track when this occurs, allied to the onDestroy and onPause methods. The precision in that case will be as good as you want. You can call an alarm every minute to check it for example, or run a background service in its own process that will remain active after the application is killed.

There's a comprehensive discussion about this in another question. It's about native code, but the explanation of the problem is very useful for you to understand the limits of the framework.

Community
  • 1
  • 1
Luís Brito
  • 1,652
  • 1
  • 17
  • 34