繁体   English   中英

android:CurrentLocation始终返回null值

[英]android : CurrentLocation always return null value

我试图使用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);
            }

请帮我。

实际上答案是非常有用的,所以这是我对这个问题所做的事情。问题是因为我已经在onCreate()实现的方法中编写了转到当前位置的完整代码,并将getLastLocation设置为null我猛烈地写了连接

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);

有几个原因使您成为null。 最有可能的是,它没有先前的位置可以拉出。 请记住,getLastLocation实际上并不会外出并获得新的位置; 它只是抓住了手机的最后一个。 您的手机将从各种来源/方法中获取位置数据,这就是所使用的数据。 根据我的经验,它通常只有几分钟的时间。

我会:

1)检查您是否未使用SIM卡2)检查您的GPS是否在手机上运行(Google Maps是否正常工作?)3)尝试强制进行位置更新(LocationManager.requestLocationUpdate(...),如此处所示 )和从那里调试。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM