GPS是否甚至需要打开ACCESS_COARSE_LOCATION?

时间:2018-07-14 10:41:32

标签: android location

我可以通过GPS获得精确的位置,但是如果我试图通过网络提供商获得大致的位置,我是否仍需要打开用户GPS?请帮忙。谢谢。

编辑: 我正在附上代码。这是我的MainActivity.java文件。请看看。

public class MainActivity extends AppCompatActivity {

private static int ACCESS_CODE = 1;
private TextView text;
LocationManager locationManager;
LocationListener locationListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = findViewById(R.id.text);

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED)) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, ACCESS_CODE);
    } else {
        updateLocation();
    }
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Toast.makeText(MainActivity.this,"hi",Toast.LENGTH_SHORT).show();
            double latitude = location.getLatitude();
            text.setText("LATITUDE: "+latitude);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    };
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == ACCESS_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            updateLocation();
        }
    }
}

public void updateLocation() {
    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED)) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, ACCESS_CODE);
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0,locationListener);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    locationListener.onLocationChanged(location);
}

}

1 个答案:

答案 0 :(得分:1)

否,在使用ACCESS_COARSE_LOCATION时不需要打开用户的GPS。 使用上述方法时,您会从网络提供商处获得位置更新,并且比精确位置要精确得多。

希望有帮助。