我的应用程序包含以下代码,以检查使用设备的位置服务的权限,但我需要某种方式来检测设备中的Location
是打开还是关闭,如果关闭则将其打开。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_counties)
// selectedCounty = intent.getStringExtra("COUNTY")!!
// Custom action bar code to return to list of counties
// configureCustomActionBar()
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Log.d("Debug","Permission not granted")
// Permission is not granted
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(this, "Location needed for navigation", Toast.LENGTH_SHORT).show()
} else {
Log.d("Debug","Request Permission")
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_CODE)
}
} else {
// Permission has already been granted
Log.d("Debug", "Permission already granted")
}
}
尽管已授予权限,但我仍然需要某种方式打开Location
或提示用户手动将其打开。
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();
}
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
// Alert user to switch Location on in Settings
val builder = AlertDialog.Builder(this)
// Set the alert dialog title
builder.setTitle("Turn on \"Location\"")
// Display a message on alert dialog
builder.setMessage("\"Location\" is currently turned off. Turn on \"Location\" to enable navigation function in GoSiteUK")
// Set a positive button and its click listener on alert dialog
builder.setPositiveButton("OK"){dialog, which ->
val intent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
// Display a negative button on alert dialog
builder.setNegativeButton("Cancel"){dialog,which ->
val intent = Intent(this, CountriesActivity::class.java)
startActivity(intent)
}
// Finally, make the alert dialog using builder
val dialog: AlertDialog = builder.create()
// Display the alert dialog on app interface
dialog.show()