Android GPS_PROVIDER始终返回null

时间:2017-07-23 15:18:07

标签: java android gps android-gps

我正在开发一款应用,当我尝试获取Android的位置时,我总是得到null

我尝试使用真实设备,运行API 19并启用GPS

这是我的代码:

double latitud, longitud;    
Location location;
LocationManager mlocManager;
LocationListener locationListener;
String provider;

    final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!gpsEnabled) {
        Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(settingsIntent);
    }
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
        return;
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    provider = mlocManager.getBestProvider(criteria, true);
    Log.i("PROVIDER", provider);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitud = location.getLatitude();
            longitud = location.getLongitude();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {


        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };
    mlocManager.requestLocationUpdates(provider, 0, 0,locationListener);
    location = mlocManager.getLastKnownLocation(provider);
    if (location != null) {            
        latitud = location.getLatitude();
        longitud = location.getLongitude();
        Log.i("LATITUD GPS", String.valueOf(latitud));
        Log.i("LONGITUD GPS", String.valueOf(longitud));


    } else {
        Log.e("LOCATION", "null");            
    }
}

我尝试使用LocationManager.GPS_PROVIDER代替Criteria,但它不起作用。

提前致谢。

0 个答案:

没有答案