android-getLastLocation()在GoogleApiClient中始终为null

android-getLastLocation()在GoogleApiClient中始终为null,第1张

概述我正在尝试构建一个使用GoogleClientApi和LocationServices请求当前位置的应用程序,但是即使我启用了WiFi,移动数据和GPS并在多台设备上对其进行了相同测试,该位置也始终为null来自manifest.xml的权限:<uses-permissionandroid:name="com.google.android.providers.gsf.permissi

我正在尝试构建一个使用GoogleClIEntAPI和LocationServices请求当前位置的应用程序,但是即使我启用了WiFi,移动数据和GPS并在多台设备上对其进行了相同测试,该位置也始终为null

来自manifest.xml的权限:

<uses-permission androID:name="com.Google.androID.provIDers.gsf.permission.READ_GSERVICES" /><uses-permission androID:name="androID.permission.ACCESS_COARSE_LOCATION" /><uses-permission androID:name="androID.permission.ACCESS_FINE_LOCATION" />

活动:

public class FindStation extends Fragment implements Googleapiclient.ConnectionCallbacks,Googleapiclient.OnConnectionFailedListener,com.Google.androID.gms.location.LocationListener{    public static FragmentManager fragmentManager;    button gobutton;    Spinner spinner;    SupportMapFragment mapFragment;    GoogleMap map;    List<Stations> stationsList;    ArrayList<String> stationsAddresses;    private static VIEw vIEw;    ArrayList<MarkerOptions> markers;    Googleapiclient mGoogleapiclient;    LocationServices locationServices;    Location location;    private static String TAG="FIND_STATION";    Context context;    LocationRequest mLocationRequest;    LocationListener locationListener;    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater, @Nullable VIEwGroup container, @Nullable Bundle savedInstanceState) {        context= getActivity();        locationListener=this;        mLocationRequest = new LocationRequest();        mLocationRequest.setInterval(10000);        mLocationRequest.setFastestInterval(5000);        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);        mLocationRequest.setSmallestdisplacement(10);        /*mGoogleapiclient = new Googleapiclient.Builder(getActivity())                .addAPI(LocationServices.API)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .build();*/        buildGoogleapiclient();        if (vIEw != null) {            VIEwGroup parent = (VIEwGroup) vIEw.getParent();            if (parent != null)                parent.removeVIEw(vIEw);        }        try {            vIEw = inflater.inflate(R.layout.activity_find_station, container, false);        } catch (InflateException e) {        }              inflater.inflate(R.layout.activity_find_station,container,false);        stationsAddresses = new ArrayList<>();        gobutton= (button) vIEw.findVIEwByID(R.ID.button);        //gobutton.setVisibility(VIEw.INVISIBLE);        spinner= (Spinner) vIEw.findVIEwByID(R.ID.spinner);        stationsList = Stations.ListAll(Stations.class);        markers = new ArrayList<>();        for (int i = 0; i <stationsList.size() ; i++) {            stationsAddresses.add(stationsList.get(i).getStationLocation());            markers.add(new MarkerOptions().position(new LatLng(stationsList.get(i).getStationLat(), stationsList.get(i).getStationLong())).Title(stationsList.get(i).getStationname()));        }        gobutton.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                //location= LocationServices.FusedLocationAPI.getLastLocation(mGoogleapiclient);            }        });        try {            initialize();        } catch (Exception e) {            e.printstacktrace();        }        try {           // map.setMyLocationEnabled(true);        } catch (Exception e) {            e.printstacktrace();        }        /*thread = new Thread(new MyThread());        thread.start();*/        return vIEw;    }    private voID initialize() {        if (map==null) {            Fragment fragment= getChildFragmentManager().findFragmentByID(R.ID.map);            mapFragment= (SupportMapFragment) fragment;            map=mapFragment.getMap();            for (int i = 0; i <markers.size() ; i++) {              map.addMarker(markers.get(i));            }            // check if map is created successfully or not            if (map==null) {                Toast.makeText(super.getActivity(),                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)                        .show();            }        }    }    public voID onDestroyVIEw() {        super.onDestroyVIEw();        androID.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();        SupportMapFragment fragment = (SupportMapFragment) fm.findFragmentByID(R.ID.map);        if (fragment!=null) {                androID.support.v4.app.FragmentTransaction ft = fm.beginTransaction();                ft.remove(fragment);                ft.commit();        }    }    @OverrIDe    public voID onConnected(Bundle bundle) {        location= LocationServices.FusedLocationAPI.getLastLocation(mGoogleapiclient);        if (location!=null){            Log.d(TAG,location.toString());        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),3f);        map.animateCamera(update);        }        Log.d(TAG,"connected");    }    @OverrIDe    public voID onConnectionSuspended(int i) {        Log.d(TAG,"connection suspended "+String.valueOf(i));    }    @OverrIDe    public voID onConnectionFailed(ConnectionResult connectionResult) {        Log.d(TAG,"connection Failed");    }    @OverrIDe    public voID onLocationChanged(Location location) {`enter code here`        Log.d(TAG,location.toString());        this.location=location;        if (location!=null) {            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 3f);            map.animateCamera(update);            Log.d(TAG, "camera updated to new position");            gobutton.setVisibility(VIEw.VISIBLE);        }    }    @OverrIDe    public voID onStart() {        super.onStart();        mGoogleapiclient.connect();        Log.d(TAG,"connect() was called");    }    protected synchronized voID buildGoogleapiclient() {        mGoogleapiclient = new Googleapiclient.Builder(context)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addAPI(LocationServices.API)                .build();    }}

奇怪的是,调用了onConnect()方法,但是之后Location始终为null,并且从未调用过onLocationChanged()

使用地图,我尝试启用我的位置,当您在右上角具有按钮时,它可以工作,它可以返回位置并为相机设置动画.

更新1

更新了onConnected()方法并使其请求位置更新,

public voID onConnected(Bundle bundle) {    LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, locationListener);    if (location!=null){        Log.d(TAG,location.toString());    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),3f);    map.animateCamera(update);    }    Log.d(TAG,"connected");}

然后用一个按钮我叫lastKNownLocation()因为onLocationChanged()还没有被调用,并且返回的Location仍然是null

更新2:

相同的代码在AndroID 5.0.1上也能正常工作
所有其他设备都在androID 2.3.7,4.0.1上运行,但都不起作用,

关于位置的AndroID API有什么不同的想法吗?

解决方法:

您需要调用requestLocationUpdates()才能注册侦听器并调用onLocationChanged().

确保尽快取消注册监听器,以免消耗过多电池.

还要注意,getLastLocation()方法可以并且将返回null.主要问题是它不会提示向 *** 作系统请求新的位置锁定,而是仅检查其他应用程序的位置请求中是否存在最后一个已知的位置.如果最近没有其他应用发出位置请求,那么您将得到一个空位置.

确保您实际获得位置的唯一方法是请求一个位置,这是通过调用requestLocationUpdates()完成的.

这是一个可供参考的工作示例:

public class MainActivity extends FragmentActivity        implements OnMapReadyCallback,        Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener,        LocationListener {    private GoogleMap map;    private LocationRequest mLocationRequest;    private Googleapiclient mGoogleapiclient;    private Location mLastLocation;    private Marker marker;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);    }    @OverrIDe    protected voID onResume() {        super.onResume();        buildGoogleapiclient();        mGoogleapiclient.connect();        if (map == null) {            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()                    .findFragmentByID(R.ID.map);            mapFragment.getMapAsync(this);        }    }    @OverrIDe    public voID onMapReady(GoogleMap retMap) {        map = retMap;        setUpMap();    }    public voID setUpMap(){        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);        map.setMyLocationEnabled(true);    }    @OverrIDe    protected voID onPause(){        super.onPause();        if (mGoogleapiclient != null) {            LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleapiclient, this);        }    }    protected synchronized voID buildGoogleapiclient() {        Toast.makeText(this, "buildGoogleapiclient", Toast.LENGTH_SHORT).show();        mGoogleapiclient = new Googleapiclient.Builder(this)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addAPI(LocationServices.API)                .build();    }    @OverrIDe    public voID onConnected(Bundle bundle) {        Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();        mLocationRequest = new LocationRequest();        mLocationRequest.setInterval(1000);        mLocationRequest.setFastestInterval(1000);        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);        //mLocationRequest.setSmallestdisplacement(0.1F);        LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, this);    }    @OverrIDe    public voID onConnectionSuspended(int i) {        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();    }    @OverrIDe    public voID onConnectionFailed(ConnectionResult connectionResult) {        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();    }    @OverrIDe    public voID onLocationChanged(Location location) {        mLastLocation = location;        //remove prevIoUs current location Marker        if (marker != null){            marker.remove();        }        double dLatitude = mLastLocation.getLatitude();        double dLongitude = mLastLocation.getLongitude();        marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))                .Title("My Location").icon(BitmapDescriptorFactory                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));    }}

还有一件事,如果地图在Fragment中,则不需要嵌套的SupportMapFragment.您可以让您的Fragment扩展SupportMapFragment.这消除了具有嵌套Fragment的需要,您甚至不需要膨胀任何布局xml,这是一个简单的示例:

public class MapTabFragment extends SupportMapFragment                                     implements OnMapReadyCallback {    private GoogleMap mMap;    private Marker marker;    public MapTabFragment() {    }    @OverrIDe    public voID onResume() {        super.onResume();        setUpMAPIfNeeded();    }    private voID setUpMAPIfNeeded() {        if (mMap == null) {            getMapAsync(this);        }    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap) {        mMap = GoogleMap;        setUpMap();    }    private voID setUpMap() {        mMap.setMyLocationEnabled(true);        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);        mMap.getUiSettings().setMapToolbarEnabled(false);        mMap.setonMapClickListener(new GoogleMap.OnMapClickListener() {            @OverrIDe            public voID onMapClick(LatLng point) {                //remove prevIoUsly placed Marker                if (marker != null) {                    marker.remove();                }                //place marker where user just clicked                marker = mMap.addMarker(new MarkerOptions().position(point).Title("Marker")                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_magenta)));            }        });    }}
总结

以上是内存溢出为你收集整理的android-getLastLocation()在GoogleApiClient中始终为null全部内容,希望文章能够帮你解决android-getLastLocation()在GoogleApiClient中始终为null所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1089919.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存