Risposte:
Il modo migliore sembra essere il seguente:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
alertper l'intera attività in modo da poterla eliminare in onDestroy per evitare una perdita di memoria ( if(alert != null) { alert.dismiss(); })
LocationManager.NETWORK_PROVIDERrestituirà true
In Android, possiamo facilmente verificare se il GPS è abilitato nel dispositivo o meno utilizzando LocationManager.
Ecco un semplice programma da controllare.
GPS abilitato o meno: - Aggiungi la riga di autorizzazione utente di seguito in AndroidManifest.xml per accedere alla posizione
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Il tuo file di classe java dovrebbe essere
public class ExampleApp extends Activity {
/** Called when the activity is first created. */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
L'output sarà simile


alertper l'intera attività in modo da poterlo ignorare onDestroy()per evitare una perdita di memoria ( if(alert != null) { alert.dismiss(); })
sì Le impostazioni GPS non possono più essere modificate in modo programmatico poiché sono impostazioni di privacy e dobbiamo verificare se sono attive o meno dal programma e gestirle se non sono accese. puoi avvisare l'utente che il GPS è spento e utilizzare qualcosa del genere per mostrare all'utente la schermata delle impostazioni, se lo desideri.
Controlla se i provider di posizione sono disponibili
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available
startFetchingLocation();
}else{
// Notify users and show settings if they want to enable GPS
}
Se l'utente desidera abilitare il GPS, è possibile mostrare la schermata delle impostazioni in questo modo.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);
E nel tuo onActivityResult puoi vedere se l'utente lo ha abilitato o meno
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE && resultCode == 0){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available.
// Do whatever you want
startFetchingLocation();
}else{
//Users did not switch on the GPS
}
}
}
Questo è un modo per farlo e spero che aiuti. Fammi sapere se sto facendo qualcosa di sbagliato.
startActivityForResultcon più intenti. Quando gli intenti tornano alla tua attività, controlla il RequestCode per vedere quale intento sta tornando e rispondere di conseguenza.
providerpuò essere una stringa vuota. Ho dovuto cambiare l'assegno in(provider != null && !provider.isEmpty())
Ecco i passaggi:
Passaggio 1: creare servizi in esecuzione in background.
Passaggio 2: è richiesta la seguente autorizzazione anche nel file manifest:
android.permission.ACCESS_FINE_LOCATION
Passaggio 3: scrivere il codice:
final LocationManager manager = (LocationManager)context.getSystemService (Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();
Step 4: O semplicemente puoi controllare usando:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Passaggio 5: eseguire i servizi continuamente per monitorare la connessione.
Sì, puoi controllare di seguito il codice:
public boolean isGPSEnabled (Context mContext){
LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
Questo metodo utilizzerà il servizio LocationManager .
Link alla fonte
//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return statusOfGPS;
};
Il GPS verrà utilizzato se l'utente gli ha consentito di utilizzarlo nelle sue impostazioni.
Non puoi più attivarlo esplicitamente, ma non è necessario: è davvero un'impostazione di privacy, quindi non vuoi modificarlo. Se l'utente è d'accordo con le app che ottengono coordinate precise, sarà attivo. Quindi l'API del gestore della posizione utilizzerà il GPS, se possibile.
Se la tua app non è davvero utile senza GPS ed è disattivata, puoi aprire l'app delle impostazioni nella schermata giusta usando un intento in modo che l'utente possa abilitarlo.
Questo pezzo di codice controlla lo stato del GPS
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
`
Nel tuo LocationListener, attrezzo onProviderEnablede onProviderDisabledgestori di eventi. Quando chiami requestLocationUpdates(...), se il GPS è disabilitato sul telefono, onProviderDisabledverrà chiamato; se l'utente abilita il GPS, onProviderEnabledverrà chiamato.
In Kotlin: - How to check GPS is enable or not
val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkGPSEnable()
}
private fun checkGPSEnable() {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
->
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
})
.setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
val alert = dialogBuilder.create()
alert.show()
}