You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms如何拦截Android应用手动终止事件以清理残留本地通知

Xamarin.Forms 本身未提供跨平台的应用终止生命周期统一回调,该需求需要依赖原生平台能力分别实现,iOS 端你已经通过 AppDelegate.WillTerminate 完成实现,以下是 Android 端的可行落地方案:

Android 端实现

1. 处理用户手动终止应用场景

你的位置追踪逻辑本身需要后台持续运行,建议使用 Android 前台服务实现位置追踪,同时重写服务的 OnTaskRemoved 方法,该方法会在用户从最近任务列表手动划掉应用时触发,可直接在该方法内处理通知逻辑:

[Service]
public class LocationTrackingService : Service
{
    // 你原有服务的其他逻辑省略
    public override void OnTaskRemoved(Intent rootIntent)
    {
        // 清除残留的位置追踪激活通知
        var notificationManager = GetSystemService(NotificationService) as NotificationManager;
        notificationManager.Cancel(/* 你的追踪通知固定ID */);
        
        // 可选:发送追踪随应用终止停止的通知
        var stopNotification = /* 构建你的通知实例 */;
        notificationManager.Notify(/* 新通知ID */, stopNotification);
        
        base.OnTaskRemoved(rootIntent);
        StopSelf();
    }
}

2. 处理应用崩溃场景

注册 Android 全局未处理异常回调,在应用崩溃触发回调时执行通知清除逻辑:
在 Android 项目的 MainApplication.OnCreate 或者 MainActivity.OnCreate 方法中添加如下代码:

// 捕获.NET 层未处理异常
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    ClearNotificationLogic(); // 调用你封装的通知清除方法
};
// 捕获 Android 原生层未处理异常
Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) =>
{
    ClearNotificationLogic();
    // 可根据你的崩溃处理策略调整是否标记为已处理
    // args.Handled = true;
};

跨平台逻辑复用

你可以通过 Xamarin.Forms 依赖服务封装统一的通知操作,避免双端逻辑重复:

  1. 在共享项目中定义服务接口:
public interface INotificationManager
{
    void ClearTrackingNotification();
    void SendTrackingStoppedNotification();
}
  1. iOS 和 Android 分别实现该接口,iOS 端直接在 WillTerminate 方法中调用对应方法,Android 端在上述 OnTaskRemoved 和异常回调中调用对应方法即可。

注意事项

  • Android 12(API 31)及以上版本需要动态申请 POST_NOTIFICATIONS 权限才能正常发送通知,Android 13 之后后台位置权限也需要单独申请,建议提前做权限校验。
  • 若你当前未使用前台服务实现位置追踪,Android 高版本会限制后台长期运行的位置采集行为,建议替换为前台服务实现,既符合系统权限要求也能稳定拿到应用终止的回调。

内容的提问来源于stack exchange,提问作者user2209634

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:48:02