In my application, i need to request write and read permission from the storage. Since i want to show the user that the app needs these permissions, i have created and Activity containing a button, which on click, should call the Storage permission Dialog.
However, since the recent Android changes, this doesnt work anymore.
Is there a new (and clean) way to ask permission? Am i doing something wrong?
I have added the uses-permission line inside the AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
This is the code inside the Activity:
class ActivityPermission : AppCompatActivity() {
companion object {
var PERMISSION_REQUEST_CODE = 12
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPermissionBinding.inflate(layoutInflater)
setContentView(R.layout.activity_permission)
binding.btnPermission.setOnClickListener {
ActivityCompat.requestPermissions(this, arrayOf(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, getString(R.string.permissiongranted), Toast.LENGTH_SHORT).show();
finish()
} else {
Toast.makeText(this, getString(R.string.permissiondenied), Toast.LENGTH_SHORT).show();
}
}
}
}
Thanks to everyone for helping me discover more about Android Permissions.
I decided to change the way i ask for the permission. Instead of an Activity, i decided to use a Fragment instead ("show an educational UI to the user. In this UI, describe why the feature, which the user wants to enable, needs a particular permission." - source | Thanks to #Michael in the comments for pointing it out).
Since now im using a Fragment, i have to use requestPermissions (Thanks to this reply). This now works flawlessly without any issues.
Turns out you need a combination of checks when trying to request a permission. You have to first check if the permission is actually enabled with checkSelfPermission, so you can easily choose where the user should go to start using the app.
Related
In Android 13, I need a basic flow to get permission for push notifications:
class MainActivity : ComponentActivity(), LocationListener {
val notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// Permission is granted. Continue the action or workflow in your
// app.
} else {
// Explain to the user that the feature is unavailable because the
// feature requires a permission that the user has denied. At the
// same time, respect the user's decision. Don't link to system
// settings in an effort to convince the user to change their
// decision.
}
}
private fun requestPushNotificationPermissions(){
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED)) {
// granted
}else {
// not granted, ask for permission
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
This is what happened:
when user first installed the app, checkSelfPermission returns not granted, and we then lauch permission launcher
user sees the permission dialog in Android 13
user selects Allow
Expected: registerForActivityResult callback will be fired with isGranted true
Actual: registerForActivityResult callback is not fired.
Same if user selects Not Allow. callback is never fired. Why?
This is my dependencies:
implementation 'androidx.activity:activity-ktx:1.2.0-alpha07'
implementation 'androidx.fragment:fragment-ktx:1.3.0-alpha07'
sadly can't help why it doesn't work. But I used EasyPermission for handling the permissons request and it works fine.
https://github.com/googlesamples/easypermissions
Turns out, the registerForActivityResult callback never fires, because somewhere in the Activity, there is this piece of old function "onRequestPermissionsResult" that is accidentally catching all permissions callback:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == locationPermissionCode) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Location permission granted
}
else {
//Location permission denied
}
}else{
//Notification permission callback accidentally landed here silently
}
}
Hope this helps someone.
I am programming an app that connects to a device via Bluetooth, but every time I want to do something with the BluetoothDevice I have to insert a permission check like this (Kotlin):
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.BLUETOOTH_CONNECT),
42
)
}
Is there a workaround with one single permission check in the beginning of the app?
Thank you!
We have to check permission granted, otherwise it may crash your app.
but we can do in very handy way in Kotlin.
Follow below steps...
In your MainActivity or Very first activity, ask Bluetooth permission like below.
Create Permission Callback in Activity.
private val requestPermissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
if (permissions.all { it.value }) Toast.makeText(
this,
"Permission Granted",
Toast.LENGTH_SHORT
).show()
else Toast.makeText(this, "not accepted all the permissions", Toast.LENGTH_LONG).show()
}
Request a permission in onCreate method of Activity.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//your code
requestPermissionsLauncher.launch(
arrayOf(android.Manifest.permission.BLUETOOTH_CONNECT)
) //asking permission whatever we need to run app.
}
Create a kotlin Extension function to make sure to run only on Bluetooth permission is Granted.
fun <T> Context.runOnBluetoothPermission(block: () -> T) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
block()
} else {
Toast.makeText(
this,
"Bluetooth permission need to work this.",
Toast.LENGTH_SHORT
).show()
}
}
Use it extension function wherever you need.
example :
In SecondActivity.kt
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//ui functions
//apicalls if any
//functions that only run on Bluetooth permission
runOnBluetoothPermission{
getAllBluetoothDevices()
}
}
private fun getAllBluetoothDevices(){
//your code to get all bluetooth devices.
}
}
The user can revoke the permission at any time, by going to the app settings. When the permission is revoked, the activity will be recreated. This means you have to check at least once after onCreate and before using the permission, if you still have the permission.
TL;DR
No, your app might crash.
I come to you in a time of great need. I am currently learning to use Kotlin for app development and as a "project" per-say, I am working on a simple "File manager". The current problem I am experiencing is that I am unable to read the directories and the files.
Using API 26
Using Kotlin
Using ViewModel
The permissions in the AndroidManifest.xml are set
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The permission request in runtime is called in MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (checkPermission()) {
//permission allowed
val path = Environment.getExternalStorageDirectory().path
val filesAndFolders: Array<File>? = File(path).listFiles()
Log.d("FILETAG", path) // /storage/emulated/0
Log.d("FILETAG", filesAndFolders.toString()) // null
Log.d("FILETAG", File(path).exists().toString()) // true
Log.d("FILETAG", File(path).canRead().toString()) // false
} else {
//permission not allowed
requestPermission()
}
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow()
}
}
}
private fun checkPermission(): Boolean {
val result =
ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_EXTERNAL_STORAGE
)
return result == PackageManager.PERMISSION_GRANTED
}
private fun requestPermission(){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage permission is required", Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
111
)
}
}
As commented in the code, the file array is returned as a "null", though the files seem to exist but are unreadable.
Additionally, I have tried executing this code from an inside of the fragment, but with the exact same results, though am required to read the files in a fragment rather than inside the MainActivity (But I first need to get this part of my code working before I move on to the fragments) and list the files in a RecyclerView.
This is my first question on Stackoverflow, if I missed any essential detail, let me know.
Please grant me your infinite knowledge, thank you.
I am new to Android App development and I'd really like to know if there is a way to check in another Class (a Foreground Service that gathers some location data) if the location Permission was given in the Main Activity.
In my main Activity, I am requesting the permission straight upon app start like this:
private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_ID
)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_ID) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "Right Permissions Granted", Toast.LENGTH_LONG).show()
}
}
}
}
Its working and I can give my app the permission to access the location. To use a function in my other I class, I need to check if the permission was granted, and I do it like this:
fun dummy(){
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
// do work that needs the location permission
}
}
However, if I try to execute this function, I get a null pointer reference. What am I missing here?
Thank you!
You can't request permissions from a Service. The reason is that when the request permission dialog comes up, the user is naturally going to think it belongs to the foreground app. THat confusion is why Google doesn't allow it. My best suggestion would be to launch an Activity that then asks for permission.
Trying to play an mp3 in the emulator's external storage (but not on an sd card). After some Googling I thought I had code that would work and also added the following lines to my app's AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
It still fails and I found posts saying that apparently I need to request permission as well. Copied in some code I found that was supposed to do so but then I got a message from Android Studio saying that using it would limit what API level it would work with. Realized then I was way out of my depth on what is the right way to accomplish my goal. Some context for what API level is reasonable or sanity checking of my MediaPlayer code would be greatly appreciated. Thanks.
class MainActivity : AppCompatActivity()
{
private lateinit var mp: MediaPlayer
private var totalTime: Int = 0
override fun onCreate( savedInstanceState: Bundle? )
{
super.onCreate( savedInstanceState )
setContentView( R.layout.activity_main )
// this is the permission code I get the API level warning about
val MY_READ_EXTERNAL_REQUEST : Int = 1
if (checkSelfPermission(
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), MY_READ_EXTERNAL_REQUEST)
}
mp = MediaPlayer()
// path and name of mp3 file I'm trying to play
mp.setDataSource( "/storage/emulated/0/Music/Bad Guys Win.mp3" )
mp.prepare()
mp.start()
}
}
Permission Error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.scratch/com.example.scratch.MainActivity}:
java.io.FileNotFoundException: /storage/emulated/0/Music/Bad Guys
Win.mp3: open failed: EACCES (Permission denied)
Screenshot of API warning from Android Studio
You are asking for permission, but you are not waiting for it to be granted. Use this callback method which is automatically called after a permission is granted:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(grantResults.size > 0 && grantResults.get(0) == PackageManager.PERMISSION_GRANTED){
// write your media player code here
}
}