2011-10-10 20 views

回答

33

您可以啓動位置設置的選項意向。

Intent gpsOptionsIntent = new Intent( 
    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
startActivity(gpsOptionsIntent); 
+1

但這樣會導致在設置屏幕上,只要你去那裏,循環返回它仍然會進入設置屏幕 –

+0

它爲什麼會導致循環? –

+1

我認爲這取決於你把這段代碼放在哪裏。如果您在應用程序恢復時啓動活動,則最終可能會出現循環。但它不是由代碼本身造成的。 –

5

你可以檢查GPS後使用

Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); 
     startActivity(intent); 

完整的源代碼可以發現HERE或者你可以參考SO ANSWER

+0

將ACTION_LOCATION_SOURCE_SETTINGS更改爲ACTION_SECURITY_SETTINGS – Xenione

+0

指向另一個SO的有用鏈接答案! –

8

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); 
    } 
1

實施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); 
} 
}