i want android override activity method in fragment - android

I want onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) method in fragment
I found google and anwser fragment
(mainActivity)getActivity.onrequestPermissionResult
but I don't know this parametor
Do you have any other way or know this parameter? All I know is requestCode
viewmodel
private val _permissionVisibility = MutableLiveData<Boolean>(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PERMISSION_GRANTED)
val permissionVisibility: LiveData<Boolean>
get() = _permissionVisibility
xml binding
android:visibility="#{homeViewModel.permissionVisibility ? View.VISIBLE : View.GONE}"
mainActivity
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Timber.d("Test ${requestCode} , ${permissions} , $grantResults ")
}

You can use new Activity Result APIs to get the result of permission and activityresult in much simplier way.
The Activity Results API provides two methods — RequestPermission and RequestMultiplePermissions . These two does exactly what their names are. Here’s a quick example code.
// Requesting Location Permission
bi.btnRequestPermission.setOnClickListener {
askLocationPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
}
// Single Permission Contract
private val askLocationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { result ->
if(result){
Log.e("TAG", "Location permnission granted")
}else{
Log.e("TAG", "Location permnission denied")
}
}
// -------------------------------------------------------------------
// Requesting Mutliple Permissions - Location & Bluetooth
bi.btnRequestPermission.setOnClickListener {
askMultiplePermissions(arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.BLUETOOTH
))
}
you have to add the following dependencies in your app’s build.gradle file.
implementation 'androidx.fragment:fragment-ktx:1.3.0-alpha04'
Check the blog for reference- https://wajahatkarim.com/2020/05/activity-results-api-onactivityresult/

Related

Android bluetooth permission granted automatically

I'm developing an APP using jetpack compose. On the onboarding screen I need to ask user for permission, but only when I ask for fine location permission, there is dialog popup. When I ask for BLUETOOTH, nothing happened. I debug my code, print log information.
Here is my button for requesting permission
Button(onClick = {
// navController.navigate(Screen.OnboardingLocationScreen.route)
Log.d("bluetooth permission", "${activity.checkSelfPermission(android.Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED}")
ActivityCompat.requestPermissions(activity,
arrayOf(
android.Manifest.permission.BLUETOOTH,
android.Manifest.permission.BLUETOOTH_SCAN,
android.Manifest.permission.BLUETOOTH_CONNECT
),
3
)
}
It turns out without asking permission, Bluetooth is already granted. I find log information is true and I receive message from onRequestPermissionsResult() without grant permission on the app.
#Deprecated("Deprecated in Java")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 3) {
Log.d("permission","bluetooth")
}
Here is log information
D/bluetooth permission: true
D/permission: bluetooth
I'm using API29 now.

function not working inside Fragment onRequestPermissionsResult why

override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Log.wtf("here grand result" , requestCode.toString(),)
Log.wtf("here grand result" , grantResults.toString(),)
if(requestCode == PERMISSION_REQUEST_ACCESS_LOCATION){
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(requireActivity(),"permission granted",Toast.LENGTH_SHORT).show()
getUserLocation()
}else{
Toast.makeText(requireActivity(),"Denied",Toast.LENGTH_SHORT).show()
}
}
}
I am always get the auto toast message from here but when location granted then i wants to call a function but this override method not working inside fragment please help me ?
Thanks in advance
Use below code to call onRequestPermissionResult method in fragment
requestPermisions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_PERMISSION_REQUEST_CODE}
Don't use ActivityCompat.requestPermission because it should called from activity only not in fragment.

Android: Check if Permisson is granted in another Class, not in the MainActivity

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.

ActivityResultCallback not invoked for RequestMultiplePermissions

I followed this tutorial to implement a new approach to request application permissions via Results API by RequestMultiplePermissions contract. Although the permission dialog is shown and permission result is propagated through the system to application preferences etc., my provided ActivityResultCallback is not notified at all.
Here are my source codes. I am aware I am not checking whether the user hasn't declined the permission already:
private fun checkPermissions() {
val permissionList = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION
)
val notGrantedPermissions = permissionList.map {
Pair(
it, ContextCompat.checkSelfPermission(
applicationContext,
it
)
)
}.filter {
it.second != PackageManager.PERMISSION_GRANTED
}
.map { it.first }
.toTypedArray()
if (notGrantedPermissions.isEmpty()) {
nextActivity()
} else {
requestPermissionLauncher.launch(notGrantedPermissions)
}
}
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { result ->
info("> requestPermissionLauncher - ${result.values}")
if (result.values.all { it }) {
nextActivity()
} else {
longToast("All permissions are required for app to work correctly")
checkPermissions()
}
}
Did I miss anything in the documentation?
Library version: androidx.activity:activity-ktx:1.2.0-alpha06
MinSdkVersion: 21
TargetSdkVersion: 29
I was up against this same issue tonight. I'm betting you're either extending AppCompatActivity or something similar. The issue with that is, when super.onRequestPermissionsResult is invoked, it falls to the FragmentActivity implementation which does not, itself, invoke the super method so the chain dies there. The quick solution is to extend ComponentActivity directly. However, if this is not feasible for your solution, you can override the method as follows:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
activityResultRegistry.dispatchResult(requestCode, Activity.RESULT_OK, Intent()
.putExtra(EXTRA_PERMISSIONS, permissions)
.putExtra(EXTRA_PERMISSION_GRANT_RESULTS, grantResults))
}
The above is a direct port from the ComponentActivity method.

Android: dynamic permission request design pattern

I am quite new in android programming. I would like to ask about startActivityForResult() and ActivityCompat.requestPermissions() function and their design. I understand that result of those functions is handled by another Activity functions (onActivityResult() and onRequestPermissionsResult() respectively). But I don't understand why is it designed this way.
Especially with ActivityCompat.requestPermissions(). Why do I have to control if I have permission (ContextCompat.checkSelfPermission()), if I don't then ask for it (ActivityCompat.requestPermissions()). And then handle in completely different function if I got this permission or not?
I would expect somethink like:
askPermission(Context context, String permission, Runnable permissionGranted, Runnable permissionDenied)
which would call permissionGranted if I already have permission or if I got it from user. With this function I would have to care just if I have permission or I don't have it.
Now I have to distunguish if I have permission and then do synchronous task or I don't have it and then do "asynchronous" task in onRequestPermissionsResult() where I very often do the same, as I do if I already have permission.
My question is: Is there some reason, why are permissions designed this way? Is there some funtion as I wrote above to allow me just say what to do if I have and what to do if i don't have permission (in functional way)? Or is there some desing pattern to easy handle permissions and starting activities for result?
Thanks for your time and some explanation if you know why is this design good.
Definitely Not a good way!
If we use inheritence concept we may solve this problem a little
we can make it synchronous like this :
//Kotlin
askForPermissions(permissionList, onPermissionsGranted = {
//If permissions given
}, onPermissionFailed = {
//If permissions not given
})
buy using inheritence :
//Kotlin
open class PermissionActivity : AppCompatActivity() {
private val PERM_REQ_CODE = 1457
private lateinit var onPermissionsGranted: () -> Unit;
private lateinit var onPermissionFailed: () -> Unit;
private lateinit var perms: Array<String>
internal fun askForPermissions(perms: Array<String>, onPermissionsGranted: () -> Unit, onPermissionFailed: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkIfOneNotHasPermission(perms)) {
//Dont have permissions
this.perms = perms
this.onPermissionsGranted = onPermissionsGranted
this.onPermissionFailed = onPermissionFailed
requestPermissions(perms, PERM_REQ_CODE)
}
} else {
onPermissionsGranted.invoke()
}
}
#RequiresApi(Build.VERSION_CODES.M)
private fun checkIfOneNotHasPermission(perms: Array<String>): Boolean {
perms.forEach {
if (checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED) {
return true
}
}
return false
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
PERM_REQ_CODE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkIfOneNotHasPermission(perms)) {
onPermissionFailed.invoke()
} else {
onPermissionsGranted.invoke()
}
} else {
onPermissionsGranted.invoke()
}
}
else -> {
onPermissionFailed.invoke()
}
}
}
}

Categories

Resources