Хорошо, уловка в том, чтобы использовать явный Broadcast Receiver здесь.В этом коде, когда GPS не подключен или выключен, будет отображаться диалоговое окно, предупреждающее вас о соединении NO Gps, нажав «Повторить», вы попадете на страницу настроек, где вы сможете включить GPS.
Явный метод для Broadcast Receiver
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
checkGPS();
}
} };
Для запроса разрешений у пользователя (Runtime Permissions)
public boolean checkLocationpermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1001);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1003);
}
return false;
} else
return true; }
Метод CheckGps
public void checkGPS() {
builder = new AlertDialog.Builder(this);
builder.setTitle("NO GPS");
if (isGPSready()) {
System.out.println("GPs Connected");
} else {
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!isGPSready()) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1001);
builder.show();
} else if (isGPSready()) {
System.out.println("the connection is succsful");
}
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.show();
} }
Метод onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
} else if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkGPS();
}
}
super.onActivityResult(requestCode, resultCode, data); }
Вот полный код
открытый класс MainActivity расширяет AppCompatActivity {
AlertDialog.Builder builder;
LocationManager mLocationManager;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//isGPSready();
checkGPS();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLocationpermission();
checkGPS();
registerReceiver(broadcastReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
public boolean isGPSready() {
mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public void checkGPS() {
builder = new AlertDialog.Builder(this);
builder.setTitle("NO GPS");
builder.setMessage("Click on Retry to get connected to GPS");
if (isGPSready()) {
System.out.println("GPs Connected");
} else {
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!isGPSready()) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1001);
builder.show();
} else if (isGPSready()) {
System.out.println("the connection is succsful");
}
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
} else if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkGPS();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public boolean checkLocationpermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1001);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1003);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
return false;
} else
return true;
}}