首页 > 解决方案 > 带有 PendingIntent 的 LocationManager.requestLocationUpdates 在 API 26 上不起作用

问题描述

我正在编写一个使用 gps 跟踪和记录设备位置的应用程序,它在 API 21 上运行良好,但是当我切换到 API 26 时它停止工作。

我使用了定期发送未决意图的请求位置更新:

public void startLocationUpdates() throws SecurityException 
{
    String provider = LocationManager.GPS_PROVIDER;


    PendingIntent pi = getLocationPendingIntent(true);
    //this method keep updating unless we specify it to stop

    mLocationManager.requestLocationUpdates(provider, 0, 0, pi);
}

我正在使用此接收器处理待处理的意图:

public class LocationReceiver extends BroadcastReceiver 
{
    private static final String TAG = "LocationReceiver";

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Log.d(TAG, "Receive an intent");
        Location= (Location)intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
        Log.d(TAG, this + " Got location from " + loc.getProvider() + ": " + loc.getLatitude() + ", " + loc.getLongitude());
    }
}

我认为这与这条线有关:

2019-02-08 21:41:05.872 1995-2015/system_process W/BroadcastQueue: Background execution not allowed: receiving Intent { act=com.pproject.runtracker.ACTION_LOCATION flg=0x10 (has extras) } to com.pproject.runtracker/.Controller.LocationReceiver

我不确定这意味着什么

标签: javaandroid

解决方案


这意味着您的应用程序不能在没有“前台”的情况下频繁请求/提供位置数据。所以你需要实现前台服务并通知GPS的使用。你不应该使用隐式广播。对于一对一链接,我使用回调模式并且它可以工作,对于一对多,您可以使用 Messenger 或 EventBus。

我也推荐使用 Fused Location Provider,因为它更省电并消除了诸如“冷启动”之类的问题。


推荐阅读