加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 播放位置服务getLastLocation返回null

发布时间:2020-12-15 04:43:53 所属栏目:Java 来源:网络整理
导读:我正在尝试收听位置更改,但有时onLocationChanged回调从未被调用,而getLastLocation返回null,而Google Maps始终完美运行. 注意 如果我重新启动设备,位置服务将仅工作约2天;之后,当谷歌地图仍然有效时,我的应用程序和the SDK example都不会正常工作. 这是我的
我正在尝试收听位置更改,但有时onLocationChanged回调从未被调用,而getLastLocation返回null,而Google Maps始终完美运行.

注意

如果我重新启动设备,位置服务将仅工作约2天;之后,当谷歌地图仍然有效时,我的应用程序和the SDK example都不会正常工作.

这是我的服务代码:

public class VisitService extends Service implements
        GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,LocationListener {

    private final IBinder mBinder = new VisitBinder();


    // A request to connect to Location Services
    private LocationRequest mLocationRequest;

    // Stores the current instantiation of the location client in this object
    private LocationClient mLocationClient;


    private boolean mLocationServiceConnected = false;

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

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

    public void startVisit() {
        if (!servicesConnected()) {
            listener.onVisitStartError();
            return;
        }

        if (mLocationServiceConnected) {
            if (isAcceptableLocation(mLocationClient.getLastLocation())) {
                Toast.makeText(this,"You have arrived!",Toast.LENGTH_LONG);
            } else {
                mVisitListener.onVisitStartError();
            }
        }    
    }

    private boolean isAcceptableLocation(Location location) {
        if (location == null) {
            Toast.makeText(this,"Location is null",Toast.LENGTH_LONG).show();
            return false;
        }

        return true;
    }


    private void initLocation() {

        if (mLocationRequest == null) {
            // Create a new global location parameters object
            mLocationRequest = LocationRequest.create();
            /*
             * Set the update interval
             */
            mLocationRequest
                    .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

            // Use high accuracy
            mLocationRequest
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            // Set the interval ceiling to one minute
            mLocationRequest
                    .setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        }

        if (mLocationClient == null) {
            mLocationClient = new LocationClient(this,this,this);
            mLocationClient.connect();
        }
    }

    /**
     * Verify that Google Play services is available before making a request.
     * 
     * @return true if Google Play services is available,otherwise false
     */
    private boolean servicesConnected() {

        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode,log the status
            Log.d(LocationUtils.APPTAG,getString(R.string.play_services_available));

            return true;
        } else {

            return false;
        }
    }

    public class VisitBinder extends Binder {
        public VisitService getService() {
            return VisitService.this;
        }
    }


    /**
     * In response to a request to start updates,send a request to Location
     * Services
     */
    private void startPeriodicUpdates() {

        mLocationClient.requestLocationUpdates(mLocationRequest,this);
        Toast.makeText(this,"Location Update Requested",Toast.LENGTH_LONG).show();
    }

    /**
     * In response to a request to stop updates,send a request to Location
     * Services
     */
    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(LocationUtils.APPTAG,"Location Services Connection faild");


    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(LocationUtils.APPTAG,"Location Services Connected");
        mLocationServiceConnected = true;
        startPeriodicUpdates();
    }

    @Override
    public void onDisconnected() {
        mLocationServiceConnected = false;
    }

    @Override
    public void onLocationChanged(Location location) {
        Toast.makeText(this,"Location has been changed",Toast.LENGTH_LONG).show();
    }
}

Android Manifest

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

解决方法

首先是一个bug.我也遇到过这个问题.

您可以尝试一种简单的解决方法.

在尝试获取最后一个位置之前请求位置更新,即在尝试使用getLastLocation()找到最后位置之前请求位置更新;

就像:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(true);
crta.setBearingRequired(true);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW); 
String provider = locationManager.getBestProvider(crta,true);
Log.d("","provider : "+provider);
// String provider = LocationManager.GPS_PROVIDER; 
locationManager.requestLocationUpdates(provider,1000,locationListener);
Location location = locationManager.getLastKnownLocation(provider);

此实现基于LocationManager.请选择位置客户端.

希望能帮助到你!

UPDATE

在这里你也可以使用onLocationChanged()方法,因为它会在每次更改位置时更新你,而getLastLocation()方法返回可能为NULL的最佳已知位置.

根据doc,GetLastLocation()方法将在极少数情况下返回NULL.但这种情况经常发生在我身上.

最新的更新

伙计们只有一个关于GPS的更新:

首先,我们需要使用GoogleApiClient而不是LocationClient类.

其次我们需要实现GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener

第三,我们需要覆盖其onConnected(),onConnectionSuspended()和onConnectionFailed()方法.

休息你很高兴去.

干杯!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读