我要求通过应用启用GPS的权限。它工作得很好,但它只出现了两次。
这是函数的代码:
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setIcon(R.drawable.ic_farm);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(KissanActivity.this,MainActivity.class);
startActivity(intent);
dialog.cancel();
}
});
alertDialog.show();
}
当我检查位置权限时,只调用此函数一次:
public Location getLocation() {
try {
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(this, "No Service Provider Available", Toast.LENGTH_LONG).show();
showSettingsAlert();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(this, "Network", Toast.LENGTH_LONG).show();
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Toast.makeText(this, "I've found your location", Toast.LENGTH_LONG).show();
textview.setText("Found Your Location");
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
textview.setText("Got Your LatLong - "+latitude+" - "+longitude);
GetWeather gw;
gw = new GetWeather();
gw.execute();
}
}
catch(SecurityException e){
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(this,"GPS",Toast.LENGTH_LONG).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
textview.setText("You Location Is \n");
textview.append("Latitude - "+latitude+" Longitude - "+longitude);
Toast.makeText(this, "Your Location Is "+latitude+" "+longitude , Toast.LENGTH_SHORT).show();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}