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

Android11/12后台定位停止 前台服务被杀死问题排查

问题背景

开发轨迹追踪类应用时,核心逻辑为获取实时位置更新后将数据存储至Realm数据库,目前已完成基础功能开发,应用在前台状态下所有逻辑运行正常,但在Android 11、Android 12版本上存在专属异常:应用进入后台一段时间后位置更新停止,顶部常驻通知同步消失,重新打开应用会从Splash启动页重新加载,判断为应用进程被系统杀死导致定位中断、通知移除,相同代码逻辑在Android 10及更低版本可正常运行。

现有实现代码

JS端定位逻辑

Geolocation.getCurrentPosition(
    position => {
      var speed = JSON.stringify(position.coords.speed);
      var accuracy = JSON.stringify(position.coords.accuracy);
      if (speed > 0 && (accuracy < 5 || accuracy > 15)) {
        var movingLongitude = JSON.stringify(position.coords.longitude);
        var movingLatitude = JSON.stringify(position.coords.latitude);

        let arr = {
          latitude: parseFloat(movingLatitude),
          longitude: parseFloat(movingLongitude),
        };

        let newArr = AppConfig.Coordinates;
        newArr.push(arr);
        AppConfig.Coordinates = newArr;
        EventRegister.emit(Constant.SAVE_COORDINATES, 
         AppConfig.Coordinates);
      }
    },
    error => {
      console.log(error.code, error.message);
    },
    options,
  );

Android端前台服务代码

public class Services extends Service {

    private static final int SERVICE_NOTIFICATION_ID = 12345;
    private static final String CHANNEL_ID = "TrackNTravel";

    private Handler handler = new Handler();
    private Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
            Context context = getApplicationContext();
            Intent myIntent = new Intent(context, Services .class);
            context.startService(myIntent);
            HeadlessJsTaskService.acquireWakeLockNow(context);
            handler.postDelayed(this, 2000);
        }
    };
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "TrackNTravel", importance);
            channel.setDescription("CHANEL DESCRIPTION");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.handler.removeCallbacks(this.runnableCode);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.handler.post(this.runnableCode);
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("TrackNTravel service")
                .setContentText("Running...")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(contentIntent)
                .setOngoing(true)
                .build();
        startForeground(SERVICE_NOTIFICATION_ID, notification);
        return START_STICKY;
    }

}

已完成验证节点

  • 首页点击启动按钮流程正常
  • 已授予应用所需基础权限
  • 服务启动后顶部状态栏可正常显示常驻通知
  • 应用处于前台时可正常完成位置更新、展示通知
问题根因

该异常是Android 11、12版本后台管控规则收紧,现有代码未适配新规范导致的,具体触发点如下:

  1. 前台服务类型未声明:Android 11开始强制要求访问位置的前台服务必须明确声明location服务类型,未声明的服务进入后台后会被系统直接判定为违规,强制终止进程。现有代码仅调用startForeground,未指定服务类型,属于高版本系统上的不合规实现。
  2. PendingIntent未适配安卓12规则:Android 12要求所有创建的PendingIntent必须明确指定可变性标志(FLAG_IMMUTABLE或FLAG_MUTABLE),现有代码仅使用FLAG_CANCEL_CURRENT,在安卓12上创建PendingIntent会直接抛出异常,导致服务崩溃。
  3. 唤醒锁逻辑错误:代码中每2秒重复调用一次acquireWakeLockNow申请唤醒锁,但从未做释放操作,Android 12对长时间持有未释放唤醒锁的应用有严格的超时查杀机制,会直接杀死对应进程、移除关联通知。
  4. 服务自启动逻辑违规:代码中通过Runnable每2秒重复调用startService拉起自身,这种循环自启逻辑在Android 12上会被判定为异常拉起行为,触发系统后台启动限制,直接拦截服务启动请求。
  5. 定位实现依赖JS线程:使用的Geolocation.getCurrentPosition是单次位置获取接口,本身不支持持续后台定位,应用退到后台后React Native的JS桥接线程优先级会被系统压低,很容易被回收,无法持续触发定位请求。
  6. 后台位置权限缺失:Android 11开始,即使用户授予了前台位置权限,应用在后台访问位置还需要单独申请ACCESS_BACKGROUND_LOCATION权限,未持有该权限的应用在后台访问位置会被系统直接拦截,甚至触发进程回收。
修复方案

按以下步骤修改即可适配Android 11、12版本:

  1. 补全清单文件配置
    在AndroidManifest.xml中添加所需权限、声明服务类型:
<!-- 前台服务基础权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- 安卓11+位置类前台服务专属权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<!-- 位置权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

<service
    android:name=".Services"
    android:foregroundServiceType="location"
    android:exported="false" />
  1. 修复服务代码兼容性问题
  • 替换startForeground调用为版本兼容写法,安卓10及以上明确传入位置服务类型
  • 修复PendingIntent创建逻辑,安卓12及以上添加可变性标志
  • 删除Runnable中循环启动服务、重复申请唤醒锁的逻辑,仅在服务创建时申请一次唤醒锁,服务销毁时主动释放
    核心修改后的onStartCommand代码示例:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    int piFlags = PendingIntent.FLAG_CANCEL_CURRENT;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        piFlags |= PendingIntent.FLAG_IMMUTABLE;
    }
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, piFlags);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("TrackNTravel service")
            .setContentText("Running...")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(contentIntent)
            .setOngoing(true)
            .build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        startForeground(SERVICE_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
    } else {
        startForeground(SERVICE_NOTIFICATION_ID, notification);
    }
    // 仅申请一次唤醒锁,不要循环调用
    // WakeLock wl = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track:wakelock");
    // wl.acquire(10*60*1000L /*10分钟超时*/);
    return START_STICKY;
}
  1. 替换定位实现逻辑
    不要在JS层用getCurrentPosition轮询获取位置,改用成熟的后台定位原生方案(比如react-native-background-geolocation库),这类库已经适配全版本安卓后台限制,定位逻辑在原生服务层运行,不依赖JS线程存活,不会因为应用退后台被回收。
  2. 补全权限申请逻辑
    针对Android 11、12版本单独做权限申请逻辑:在用户授予前台位置权限后,单独弹窗引导用户授予后台位置权限;安卓12上还需要检查用户是否授予了精确位置权限,仅授予大致位置权限会导致定位精度不足甚至无法持续获取位置。
  3. 添加电池优化引导
    原生安卓11+及部分国产ROM会对未加入电池优化白名单的应用施加额外后台限制,可以在应用内增加引导入口,跳转到系统电池优化设置页,引导用户将应用加入白名单,进一步降低进程被系统查杀的概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 23:51:26