![](/img/trans.png)
[英]android :how to get noticed when the My Location setting location service is enabled or disabled by user
[英]Android get location or prompt to enable location service if disabled
我發現這個答案的點點滴滴散落在其他帖子中,但我想在這里為其他人錄制。
如何簡單地請求用戶的GPS和/或網絡位置,如果他們沒有啟用該服務,則提示他們這樣做?
如果你想在按鈕上捕獲位置,這就是你如何做到的。 如果用戶未啟用位置服務,則會將其發送到設置菜單以啟用它。
首先,您必須將權限“android.permission.ACCESS_COARSE_LOCATION”添加到清單中。 如果您需要GPS(網絡位置不夠靈敏),請改為添加權限“android.permission.ACCESS_FINE_LOCATION”,並將“Criteria.ACCURACY_COARSE”更改為“Criteria.ACCURACY_FINE”
Button gpsButton = (Button)this.findViewById(R.id.buttonGPSLocation);
gpsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Start loction service
LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_COARSE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera, true);
if (providerName != null && locationManager.isProviderEnabled(providerName)) {
// Provider is enabled
locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener);
} else {
// Provider not enabled, prompt user to enable it
Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
[OUTERCLASS].this.startActivity(myIntent);
}
}
});
我的外部類設置了這個監聽器
private final LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
[OUTERCLASS].this.gpsLocationReceived(location);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
然后,無論何時你想停止聽這個。 您應該至少在活動的onStop方法中進行此調用。
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this.locationListener);
經過Stack Overflow上的大量答案后,我發現這種方法工作得很好,甚至不需要很多代碼。
將int GPSoff = 0
聲明為全局變量。
現在,無論您需要檢查GPS的當前狀態並重新指示用戶打開GPS,請使用以下命令:
try {
GPSoff = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if (GPSoff == 0) {
showMessageOKCancel("You need to turn Location On",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
});
}
要提示用戶啟用位置服務,您應該使用google play服務中包含的新LocationRequest,您可以在LocationRequest中找到完整的指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.