首页 > 解决方案 > 设备锁定时获取位置

问题描述

我正在尝试获取位置。当设备解锁时,一切正常,但当设备被锁定时,坐标就不会出现。

这是我的服务示例:

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener{

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

        buildGoogleApiClient();
        mGoogleApiClient.connect();

        startForeground(1131, new NotificationCompat.Builder(this, "default")
                .setContentText("App")
                .setContentTitle("App Service")
                .setSmallIcon(R.mipmap.enter_icon)
                .build());

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startCheckLocation()
    }

    private void startCheckLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        locationRequest.setFastestInterval(interval);
        locationRequest.setInterval(interval);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        Intent intent = new Intent(this, LocationService.class);
        mPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mFusedLocationClient.requestLocationUpdates(locationRequest, mPendingIntent);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, LocationService.class);
        context.startService(intent);
    }

}

我尝试使用 getBroadcast() 而不是 getService() 方法,但它的工作方式相同。

标签: androidlocation

解决方案


就我而言,我通过 FirebaseJobDispatcher 获取位置数据(谷歌推荐使用 WorkManager,但目前它是 alpha 版)。我开始每 20 分钟触发一次的工作,请求位置并将其存储到数据库。您可以在此处查看 FirebaseJobDispatcher 的示例https://github.com/firebase/firebase-jobdispatcher-android


推荐阅读