How to check permission in fragment
I have done following to check a permission inside a fragment.
if (ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Log.e("DB", "PERMISSION GRANTED");
}
Update
Since Fragment.requestPermissions
is now deprecated, Google advises using registerForActivityResult
instead.
I have done the request like this:
val permissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
// Do if the permission is granted
}
else {
// Do otherwise
}
}
permissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
For more documentation on this method you can check this link.
How to get permission result from activity in fragment?
You have
onRequestPermissionsResult
in Fragment as well.If you still want to have
onRequestPermissionsResult
centrally in yourActivity
, you need to call the method ofFragment
onRequestPermissionsResult
of yourActivity
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ACCESS_FINE_LOCATION_PERM: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, do your work....
YourFragmentClass fragment =
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
} else {
// permission denied
// Disable the functionality that depends on this permission.
}
return;
}
// other 'case' statements for other permssions
}
}
Note : There are other ways as well to interact with Fragment
from Activity
.
How to check permission on fragment using mvvm in andorid
Fragments have requestPermissions()
and onRequestPermissionsResult()
methods for requesting permissions and receiving the results of permission request.
You are using following method to request permissions, which is not correct
ActivityCompat.requestPermissions(
activity!!,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PermissionsRequestCode)
Instead you should use the following
requestPermissions(
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PermissionsRequestCode);
You should also adjust the placement of some of your conditions, I fixed some issues
class HomeFragment : Fragment() {
private val permissionsRequestCode = 123
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.let{
when{
permissionGranted() -> Log.e("granted--","granted")
shouldShowRationale() -> {}// Show the rationale UI and then request permission
else -> requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
permissionsRequestCode)
}
}
}
// this is called when user closes the permission request dialog
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
if (requestCode == permissionsRequestCode) {
if (permissions[0] == Manifest.permission.READ_EXTERNAL_STORAGE &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted, do your work
}
}
}
private fun shouldShowRationale() = ActivityCompat.shouldShowRequestPermissionRationale(
activity!!,
Manifest.permission.READ_EXTERNAL_STORAGE)
private fun permissionGranted() = ContextCompat.checkSelfPermission(
activity!!,
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
}
How to Manage the permission request code using Navigation Component?
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
This method is deprecated.
use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a ActivityResultContracts.RequestMultiplePermissions object for the ActivityResultContract and handling the result in the callback.
requestPermissions()
API is deprecated, and replaced by registerForActivityResult(ActivityResultContract, ActivityResultCallback)
passing in a ActivityResultContracts.RequestMultiplePermissions
object
for the ActivityResultContract
and handling the result in the callback.
First the activity-ktx build.gradle
module level dependency is needed for the the new API:
implementation 'androidx.activity:activity-ktx:1.3.0-beta01'
Then ActivityResultCallback
callback need to be implemented and passed as a parameter of the registerForActivityResult
. This interface has callbacks that handle the user response to the permission request dialog.
To display the permissions dialog, call the launch()
method on the instance of ActivityResultLauncher
that is returned by the registerForActivityResult
function.
So, create an instance of ActivityResultLauncher
& implement the callback to handle the user response:
private val requestPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) { // Do something if permission granted
Log.d("LOG_TAG", "permission granted by the user")
} else { // Do something as the permission is not granted
Log.d("LOG_TAG", "permission denied by the user")
}
}
Then request the permission by using the launch
function:
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
UPDATE
For requesting multiple of permissions at once: You need to pass array of
permission to launch(). ActivityResultCallback
returns a Map<String, Boolean>
with permission as key and its grant status as value:
Then use ActivityResultContracts.RequestMultiplePermissions()
as follows:
private val requestMultiplePermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.entries.forEach {
Log.e("LOG_TAG", "${it.key} = ${it.value}")
}
}
// Usage:
requestMultiplePermissions.launch(
arrayOf(
Manifest.permission.READ_CONTACTS,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA
)
)
Applying that on the shared code:
class FragmentPermission : Fragment() {
private var binding: FragmentPermisionBinding ?= null
//...
private val requestPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) { // permission is granted
proceedAfterPermission()
} else {
// handle permission denial
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
binding = FragmentPermisionBinding.inflate(inflater, container, false)
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION)
} else {
proceedAfterPermission()
}
return binding!!.root
}
//.... rest of your code
}
How to check if user has granted permission from outside an activity/fragment in android
If MusicService is service class you can get context from service.
Context context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
//then you can call requestExternalStoragePermission() using context.
//If you want context in viewmodel use HILT dependency injection library.
@ViewModelInject
public MainViewModel(MainRepository mainRepository, @ApplicationContext Context context) {
this.repository = mainRepository;
this.context = context;
}
requestPermissions in a fragment
I only added targetapi and it worked. Also, I used requestPermissions in this fragment.
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS))
{
}
else
{
//ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
//MenuFragment.requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
return super.onOptionsItemSelected(item);
}
Related Topics
Playing Bg Music Across Activities in Android
What Is the Certificate Enrollment Process
How to Connect Android with MySQL Using MySQL Jdbc Driver
Android Classnotfoundexception
How to Get Elements of Fragments Created by Viewpager in Mainactivity
Openssl Is Not Recognized as an Internal or External Command
Ksoap2 Org.Xmlpull.V1.Xmlpullparserexception Expected Start_Tag Error
Dx Bad Class File Magic (Cafebabe) or Version (0033.0000) with Adk14
Android Microsoft Office Library (.Doc, .Docx, .Xls, .Ppt, etc.)
How to Serialize Object to JSON
Android:Change App Label Programmatically
Java - Declaring from Interface Type Instead of Class
How to Convert Image to Byte Array in Java
Why Doesn't Java Throw an Exception When Dividing by 0.0
Using Client/Server Certificates for Two Way Authentication Ssl Socket on Android