1

我使用 Goole 播放服务位置 API 和 fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,looper); 获取当前位置。

但有时会在oppo、小米等中国手机上获得最后一个位置。(这些手机上有google play)

有没有办法解决这个问题?

这是我的代码:

implementation 'com.google.android.gms:play-services-location:17.0.0'

许可:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

主要代码:(监听器是我创建的接口)

    Intent locationServiceIntent = new Intent(context, LocationService .class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(locationServiceIntent);
    } else {
        context.startService(locationServiceIntent);
    }

    FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                if(listener!=null) listener.RequestFail("當前位置無法獲取定位信號!");
                cancel();
                return;
            }
            for (Location location : locationResult.getLocations()) {
                // Update UI with location data
                // ...
                updateLoc(location);
                cancel();
            }
        }
    };

    Looper looper = Looper.myLooper();
    fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,looper);

    handler=new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(listener!=null) listener.RequestFail("當前位置無法獲取定位信號!");
            cancel();
        }
    },20000);

private void updateLoc(Location l) {
    if (l != null) {
        this.lng = l.getLongitude();
        this.lat = l.getLatitude();
        if(listener!=null){
            listener.LocationUpdate(l.getLatitude()+","+l.getLongitude());
        }
    }
}
4

0 回答 0