我需要獲取用戶的位置。我把清單如何提示用戶啓用GPS_PROVIDER和/或NETWORK_PROVIDER?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如何提示用戶啓用GPS_PROVIDER和/或NETWORK_PROVIDER?
我需要獲取用戶的位置。我把清單如何提示用戶啓用GPS_PROVIDER和/或NETWORK_PROVIDER?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如何提示用戶啓用GPS_PROVIDER和/或NETWORK_PROVIDER?
您可以啓動位置設置的選項意向。
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
LOCATION_MODE將LOCATION_MODE_OFF如果GPS是關閉的,這將返回值爲0
int off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
if(off==0){
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
實施LocationListner:所以
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider)
{
if (provider.equals(LocationManager.GPS_PROVIDER))
{
showGPSDiabledDialog();
}
}
顯示對話框打開設置:
public void showGPSDiabledDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("GPS Disabled");
builder.setMessage("Gps is disabled, in order to use the application properly you need to enable GPS of your device");
builder.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), GPS_ENABLE_REQUEST);
}
}).setNegativeButton("No, Just Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
mGPSDialog = builder.create();
mGPSDialog.show();
}
在你onCreate方法調用:
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
而且ovveride onActivityResult方法來測試是否正確激活用戶GPS
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GPS_ENABLE_REQUEST)
{
if (mLocationManager == null)
{
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
showGPSDiabledDialog();
}
}
else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
但這樣會導致在設置屏幕上,只要你去那裏,循環返回它仍然會進入設置屏幕 –
它爲什麼會導致循環? –
我認爲這取決於你把這段代碼放在哪裏。如果您在應用程序恢復時啓動活動,則最終可能會出現循環。但它不是由代碼本身造成的。 –