正在尝试通过手机信号塔获取位置,但仍然 returns null

Trying to get location with cell tower but still returns null

我想做的是从用户那里获取位置信息。首先它尝试通过 GPS 获取位置并检查位置是否可用。如果不是,则它会尝试通过网络塔。当 GPS 打开时,它工作正常。但是当我关闭 GPS 时,它无法使用网络提供商获取位置

 manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = manager.getBestProvider(new Criteria(), false);

    Log.i("ITEMSET best", provider);


    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    Log.i("ITEMSET provider", provider);

    location = manager.getLastKnownLocation(provider);
    Log.i("ITEMSET netLoc", location + "");
    if(location==null) {
        provider = LocationManager.NETWORK_PROVIDER;
        location = manager.getLastKnownLocation(provider);
        Log.i("ITEMSET netLoc", location + "qqq");
    }



    Log.i("ITEMSET current", provider);
    Log.i("ITEMSET location", location  + "");

位置最初为空,因为 GPS 未打开。但随后将提供商更改为网络提供商。但位置仍然为空

检查网络是否启用

 isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

然后:

     if (isNetworkEnabled) {
   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,10, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();


                    }
                }

您应该使用 GoogleApiClient 获取您的位置。请访问 this post