在android中通过滑动杀死应用程序时如何执行代码? [英] How to execute code when app is killed by swiping in android?
问题描述
所以基本上我在 xamarin 上使用 C# 创建了一个应用程序,一切运行完美.我调用了一个事件处理程序,当我在 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
}
问题是,当我编写上面的代码时,我收到一条错误消息错误 CS0115 'MainActivity.OnTaskRemoved(Intent)':找不到合适的方法来覆盖"
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
推荐答案
向您的项目添加 Android 服务并覆盖 OnTaskRemoved
方法:
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;
}
}
在您的应用程序启动时启动服务,或者使用启动完成并在需要时使其sticky
,等等...:
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)));
然后,当有人从最近的应用列表中删除您的应用(滑动或关闭窗口)时,OnTaskRemoved
会被调用.在这个例子中,只记录事件:
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
这篇关于在android中通过滑动杀死应用程序时如何执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!