尝试使用单元格塔获取位置但仍返回null

时间:2017-09-06 07:30:39

标签: android gps

我要做的是从用户那里获取位置。首先,它尝试通过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  + "");

Logcat

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

2 个答案:

答案 0 :(得分:1)

检查网络是否已启用

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


                    }
                }

答案 1 :(得分:1)

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