首页 > 解决方案 > 华为 mya-L22 将应用程序置于后台并关闭屏幕时 GPS 位置更新停止更新

问题描述

我有一个带有前台服务的 android 应用程序,它监听 g​​ps 位置更新,我只使用带有 gps 提供程序的 LocationManager。

我有这段代码:

        Intent intent = new Intent(this, LocationUpdateReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, this.INTERVAL, 0.0f, pi);

我正在通过接收器获取位置更新。屏幕打开时它可以正常工作,但是当我关闭设备屏幕时,它会停止获取位置更新。它正在我的 redmi 5 设备上运行,并且按预期工作。但是我的问题出现在华为上。

注意:this.INTERVAL = 10000; 我正在使用 wakeLock 来防止设备休眠,如下所示:

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG:");
    wakeLock.aquire();

我在 Manifist.xml 中的服务也是这样

          <service android:name="com.arttech.services.LocationService" android:enabled="true" />

最后,我正在显示前台服务的通知,如下所示:

    Notification.Builder ongoing = new Notification.Builder(getBaseContext()).setSmallIcon(R.drawable.logo).setContentTitle("Location Service").setOngoing(true);
    if (Build.VERSION.SDK_INT >= 26) {
        ongoing.setChannelId("myChannelID");

    }
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(NOTIFICATIONID, ongoing.build());     

任何人都可以帮助我解决这个问题吗?我挣扎了一个多月,我无处可去。

谢谢

更新:

我还尝试通过电池设置手动将我的应用程序添加为受保护的应用程序,但我得到了相同的行为。我测试了一个名为 relive 的应用程序,它完美地记录了 GPS 位置。我究竟做错了什么?

更新:这是我的 OnStartCommand 代码:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d("omar","Service Started");
    LocationObserver.getInstance().addObserver(this);


    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8)
    {
        Log.d("omar_build",SDK_INT+"");

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);


    }

    CreateConnectionInstance(); // Connect to socket

    startTracking();
    isLocationServiceRunning = true;

    return START_STICKY;
}

标签: androidservicelocationhuawei-mobile-services

解决方案


这可能是由于华为和其他一些自定义品牌所施加的限制。您应该将您的应用添加到手机白名单中。请查看以下链接 How to WhiteList app in Doze mode Android 6.0

更新:进行这两项更改,然后检查

  1. 获取唤醒锁到 onStartCommand
  2. 获取大约时间的唤醒锁
  3. 当服务销毁或服务工作完成时释放你的唤醒锁

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);

        if (powerManager != null)
            mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);

        if (mWakeLock != null)
            mWakeLock.acquire(TimeUnit.HOURS.toMillis(10));

推荐阅读