简体   繁体   中英

How to execute code when app is killed by swiping in android?

so basically i created an app using C# on xamarin and everything runs perfect. i called an event handler that when i press back button on android it doesen`t exit the app but it just moves it on background. For that i used :

public override void OnBackPressed()
    {
        MoveTaskToBack(true);
    }

Now i want that if the user wants to kill the app with swiping from task i want it to execute a code just before closing. I did some research and figured out i should use something like :

public override  void OnTaskRemoved( )
    {
    //the code here
    }

The problem is that when i write the above code i get an error saying "Error CS0115 'MainActivity.OnTaskRemoved(Intent)': no suitable method found to override"

If i remove override there is no error but the code i put inside is not executed when app is killed with swipe. Can someone help with this ? Thanks

Add an Android Service to your project and override the OnTaskRemoved method:

[Service(Label = "TaskEndService")]
[IntentFilter(new String[] { "com.sushihangover.TaskEndService" })]
public class TaskEndService : Service
{
    IBinder binder;

    public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
    {
        return StartCommandResult.NotSticky;
    }

    public override IBinder OnBind(Intent intent)
    {
        binder = new TaskEndServiceBinder(this);
        return binder;
    }

    public override void OnTaskRemoved(Intent rootIntent)
    {
        Log.Info("SO", $"{GetType().Name} just got killed....");
        base.OnTaskRemoved(rootIntent);
    }
}

public class TaskEndServiceBinder : Binder
{
    readonly TaskEndService service;

    public TaskEndServiceBinder(TaskEndService service)
    {
        this.service = service;
    }

    public TaskEndService GetTaskEndService()
    {
        return service;
    }
}

Start up the Service when your app starts, or use boot completed and make it sticky if needed, etc...:

StartService(new Intent(this, typeof(TaskEndService)));

Then when someone removes your app from the recent app list (swipe or window close tap), the OnTaskRemoved gets called. In this example, just logging the event:

05-04 19:31:27.635  3690  3690 I SO : TaskEndService just got killed....
05-04 19:31:27.636   543   909 I ActivityManager: Killing 3690:com.sushihangover.service_exit_foo/u0a83 (adj 1001): remove task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM