android:CurrentLocation总是返回null值

时间:2016-03-23 18:12:49

标签: android

我试图使用android studio获取当前位置但总是变量currentLocation具有空值

和android studio在

下划出红线
    Location currentLocation= LocationServices.FusedLocationApi.getLastLocation(mLocationclient);

并要求检查许可 我尝试了两种检查权限的方法 但是相同的结果返回空值

请问谁可以帮帮我? 这是我用过的代码


    private GoogleApiClient mLocationclient;
mLocationclient=new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mLocationclient.connect();

            Location currentLocation= LocationServices.FusedLocationApi.getLastLocation(mLocationclient);
            if(currentLocation==null)
                Toast.makeText(this,"could not connect",Toast.LENGTH_SHORT).show();
            else {
                LatLng ll=new LatLng(
                        currentLocation.getLatitude(),
                        currentLocation.getLongitude()
                );
                CameraUpdate update=CameraUpdateFactory.newLatLngZoom(ll,50);
                mMap.animateCamera(update);
            }


请帮帮我。

2 个答案:

答案 0 :(得分:2)

实际上,回答的答案非常有帮助 所以这就是我对这个问题所做的 问题是因为我已经编写了完整代码,用于转到onCreate()实现方法中的当前位置 在这个位置,getLastLocation为null 我做了什么 我jast写了连接

private GoogleApiClient mLocationclient;            

mLocationclient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            mLocationclient.connect();

然后我去当前位置听按钮clickListener 像这段代码我已编码到clickListener

LatLng ll=null;
    Location currentLocation= LocationServices.FusedLocationApi.getLastLocation(mlocationclient);
    if(currentLocation==null)
        Toast.makeText(context,"could not connect",Toast.LENGTH_SHORT).show();
    else {
            ll=new LatLng(
                currentLocation.getLatitude(),
                currentLocation.getLongitude()
        );
    }



 CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 17);


mMap.moveCamera(update);

答案 1 :(得分:0)

有几个原因让你变空。最有可能的是,它没有先前的位置。请记住,getLastLocation实际上并没有出去并获得一个新的位置;它只抓住你手机上的最后一个。您的手机将从各种来源/方法中获取位置数据,这是正在使用的数据。根据我的经验,它往往长达几分钟。

我会:

1)检查您是否使用过SIM卡 2)检查您的GPS是否在您的手机上工作(谷歌地图是否正常工作?) 3)尝试强制进行位置更新(LocationManager.requestLocationUpdate(...)为seen here)并从那里进行调试。

我相信只要您还支持SDK< 21,检查权限就是警告。

相关问题