我發現這個答案的零散部分通過其他帖子散播,但我想在這裏爲其他人記錄它。Android獲取位置或提示以啓用位置服務,如果禁用
我該如何簡單地請求用戶的GPS和/或網絡位置,如果他們還沒有啓用服務,提示他們這樣做?
我發現這個答案的零散部分通過其他帖子散播,但我想在這裏爲其他人記錄它。Android獲取位置或提示以啓用位置服務,如果禁用
我該如何簡單地請求用戶的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);
要提示用戶啓用定位服務,你應該使用包含在谷歌播放服務的新LocationRequest,你可以發現在LocationRequest
完整指南通過大量的堆棧溢出的答案會後,我發現這種方法工作得很好,甚至不需要很多代碼。
將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);
}
});
}
什麼是getContentResolver(),showMessageOKCancel&startActivity?他們都沒有解決 – hfz 2017-05-11 06:50:59
上getBestProvider第二個參數(locationCritera,真)檢查哪些提供商因此,理論上,您不需要檢查它是否再次啓用。 – Eduardo 2012-03-29 07:43:21