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

如何防止小米、红米设备中Recent Apps一键清理时Foreground Service停止?

小米/红米设备上Foreground Service规避「一键清理」终止的方案

在小米、红米等MIUI设备上,运行中的Foreground Service会被最近应用列表的「一键清理」(clear all)强制终止,这是MIUI专属的后台管控机制导致的,常规Android系统的Foreground Service配置无法直接规避。以下是针对该问题的可行处理方案:

  • 引导用户开启MIUI专属后台权限
    MIUI对后台应用有额外的权限限制,必须让用户手动开启相关权限才能避免服务被清理:

    1. 可以通过代码跳转到应用权限设置页:
      Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
      Uri uri = Uri.fromParts("package", getPackageName(), null);
      intent.setData(uri);
      startActivity(intent);
      
    2. 在应用内明确提示用户开启以下权限:
      • 自启动权限
      • 后台活动无限制权限
      • 部分MIUI版本需开启「后台弹出界面」权限
  • 服务终止后自动重启
    监听应用被终止的广播,在服务被清理后快速重启:

    public class RestartServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BOOT_COMPLETED.equals(action) || 
                "android.intent.action.PACKAGE_RESTARTED".equals(action)) {
                Intent serviceIntent = new Intent(context, YourForegroundService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(serviceIntent);
                } else {
                    context.startService(serviceIntent);
                }
            }
        }
    }
    

    另外,可搭配AlarmManager设置定时检查,若服务未运行则立即重启。

  • 提升Foreground Service通知优先级
    创建通知时设置最高优先级并标记为不可清除,让MIUI识别为用户关注的核心服务:

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("后台服务运行中")
            .setContentText("正在执行关键任务")
            .setSmallIcon(R.drawable.ic_notification)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setOngoing(true)
            .build();
    startForeground(NOTIFICATION_ID, notification);
    

注意:MIUI的后台管控逻辑会随版本迭代调整,部分高版本可能会限制上述保活手段;过度保活可能被判定为恶意应用,影响用户体验与上架审核。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:57:47