Skip to main content
Version: v5

Foreground Location

The entire Activity code is shown, in order to provide context for the permission specific methods.

class MainActivity : AppCompatActivity() {  override fun onCreate(savedInstanceState: Bundle?) {      super.onCreate(savedInstanceState)      setContentView(R.layout.activity_main)  }
  fun requestLocationPermission(view: View?) {      val hasLocation = checkPermissionStatus(Manifest.permission.ACCESS_FINE_LOCATION)      if (!hasLocation) {          showLocationDisclosure()      }  }
  @SuppressLint("InlinedApi")  override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {      if (requestCode == PERMISSIONS_REQUEST_CODE && permissions.isNotEmpty()) {           // If request is cancelled, the result arrays are empty.          if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {              // permission was granted          }      }  }
  private fun requestPermissions() {      if (checkPermissionStatus(Manifest.permission.ACCESS_FINE_LOCATION)) {          return      }      if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {          showPermissionRationale()      } else {          ActivityCompat.requestPermissions(this,                  arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),                  PERMISSIONS_REQUEST_CODE)      }  }
  private fun showPermissionRationale() {      AlertDialog.Builder(this)              .setTitle(R.string.location_title)              .setMessage(R.string.location_message)              .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }              .setPositiveButton(android.R.string.ok) { dialog, _ ->                  dialog.dismiss()                  ActivityCompat.requestPermissions(this,                          arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),                          PERMISSIONS_REQUEST_CODE)              }              .show()  }
  private fun showLocationDisclosure() {      val alertDialogBuilder = AlertDialog.Builder(this)              .setTitle(R.string.location_title)              .setMessage(getString(R.string.location_disclosure_message))              .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.cancel() }              .setPositiveButton(android.R.string.ok) { dialog, _ ->                  dialog.dismiss()                  requestPermissions()              }      alertDialogBuilder.show()  }
  private fun checkPermissionStatus(permission: String): Boolean {      return !shouldAskForPermissions() || ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED  }
  private fun shouldAskForPermissions(): Boolean {      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M  }
  companion object {      private const val PERMISSIONS_REQUEST_CODE = 736  }}