Reputation: 984
I get that fine locations come through GPS but if I am trying to get the coarse location by the network provider do I still need to have users GPS turned on?
EDIT: I am attaching the code. Here is my MainActivity.java file.
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);
}
}
Upvotes: 1
Views: 217
Reputation: 411
No, you do not need the user’s GPS to be on while using ACCESS_COARSE_LOCATION. When using the above, you get location updates from the network provider and is much less accurate than the fine location.
Upvotes: 1