Permission on Fragment - android

I have review other questions regarding the permission on android. But I still didnt get the solution for fragment. Why the dialog of permission is not appear ? Also, it dont show any error log. It just not appear.
I dont want to use FragmentCompat since its require import android.app.Fragment
This is my minimum sdk ver.
minSdkVersion 16
import android.support.v4.app.Fragment;
public class ComplaintFragment extends Fragment implements View.OnClickListener {
private void StartCamera(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSIONS_CAMERA);
}
else {OpenCamera();}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(ActivityCompat.checkSelfPermission(getActivity(), permissions[0]) == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case PERMISSIONS_CAMERA:
OpenCamera();
break;
}
}
}
}

Try this,
1) Give camera permission in your manifest.
<uses-permission android:name="android.permission.CAMERA" />
2) Check the permission is granted or not.
if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},1);
return;
} else {
oprnCamere();
}
3) Handel the result from request permission in onActivityResult() method in your fragment class.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 0: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission accepted.
openCamera()
} else {
//permission denied.
}
return;
}
}
}

onRequestPermissionsResult is deprecated. You should now use Activity Result to request permission in a fragment.
Her's a simple implementation:
class MyFragment : Fragment {
private val cameraPermissionResultReceiver = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {
// permission granted
} else {
// permission denied
}
}
}
private fun requestCameraPermission() {
cameraPermissionResultReceiver.launch(Manifest.permission.CAMERA)
}
}

maybe u can try copy
<uses-permission android:name="android.permission.CAMERA" /> to your maniferst

In your build.gradle(app level) place this code( targetSdkVersion 23)
defaultConfig {
applicationId "com.example.sampleproject"
minSdkVersion 9
targetSdkVersion 23
}

I rewrite your function on onRequestPermissionsResult. Please try:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_CAMERA:
if (getActivity().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
//Camera permission grant
OpenCamera();
else
Log.e("error","Oop something wrong with permission");
break;
}
Check this link too. It may be can help answer your question.

Related

Runtime Permissions not working

This is my code in OnCreate() method :
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.RECIEVE_SMS)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},1);
}
And in my onRequestPermissionsResult() method :
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
init();
}else{
finish();
}
And my Manifest file has the following permissions
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
But i'm not getting the dialog asking for the permission and i can't figure out the problem?
if your app targeting Android 6.0 and above than add runtime permission
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app
add runtime permission using below code for READ_SMS
String permission = Manifest.permission.READ_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
and than handle result like this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AccountClass.this,"permission granted", Toast.LENGTH_SHORT).show();
// perform your action here
} else {
Toast.makeText(AccountClass.this,"permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
Try this:
if (ActivityCompat.checkSelfPermission(AddnewPhotoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AddnewPhotoActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
} else {
isPermissionGranted(true);
}
isPermissionGranted(boolean); ====> Method call
public void isPermissionGranted(boolean permission) {
if (permission) {
//Your Operation
} else {
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
}
}
onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermissionGranted(true);
} else
{
isPermissionGranted(false);
}
}
}

How to check android application permissions on runtime using ContextCompat.checkSelfPermission()?

Need to check for the grant of the required permissions(specifically to read user device sms)by the android application user as per android 6 and above standards. I am specifically looking for the ContextCompat.checkSelfPermission() method described on android developer site.
See here:
link
Please follow this tutorials Here is complete source code
static final int PERMISSION_ALL = 1;
String[] PERMISSIONS =
{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
protected void runtimePermission() {
if (!hasPermission(ContactUS.this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermission(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_ALL:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted
//your logic here
} else {
//permission denied
}
break;
}
}
you can add run time permission like this
follow this steps
step 1 :- first add this permission in manifiest file
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
now, than
step 2 : ask runtime permission
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, PERMISSION_GPS_CODE);
}
step 3: finallly handle permsiion result in onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}
if the permission is granted by :
checkSelfPermission(Manifest.permission.READ_CONTACTS)
Request permissions if necessary
if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
/* MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant */
return;
}
Handle the permissions request response
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/* permission granted */
} else {
/* permission denied */
}
return;
}
/* check for other permissions */
}
}
Also you can use a library like this, anyway good luck!

OnResquestPermissionResult from Adapter

I Have a BaseAdapter with a List of all requires permissions for use correctly the app.
I need to, after onClick in one of them, request the permission and check if is granted or not.
For request, I am using
ActivityCompat.requestPermissions
but I do not know how to get the results.
Is it possible to call O
nRequestpermissionsResultCallback
to know the answer of the user?
How can I do it?
so first i implement in the Adapter
implements ActivityCompat.OnRequestPermissionsResultCallback
then it require one Overide method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// it is not work here onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == storagePermission) {
// getPosts(false);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context.getApplicationContext(), "Please allow permission to Continue", Toast.LENGTH_SHORT).show();
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context.getApplicationContext(), " Permissions Granted Succecfully", Toast.LENGTH_SHORT).show();
//here i load my method that i want to run
}
}
}
now problem is this onRequestPermissionsResult is not call from adapter instead
adapter triger onRequestPermissionsResult of the mainActivity Attach with the Adapter
so in main Activity i create this and run onRequestPermissionsResult of adapter by passing
adapterPosts.onRequestPermissionsResult(requestCode,permissions,grantResults);
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == storagePermission) {
// getPosts(false);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//permission not granted
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted
adapterPosts.onRequestPermissionsResult(requestCode,permissions,grantResults);
//loadImageIntent();
}
}
}
To check the permission (in this example it's a permission to use the camera):
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
// permission is not granted yet, let's ask for it
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MyActivity.cameraRequestCode);
} else {
// permission is already granted
}
If ActivityCompat.requestPermissions is run, then a dialogue appears for the user, after which you can catch the result by overriding the Activity's onRequestPermissionsResult like this:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MyActivity.cameraRequestCode: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// action when permission granted
} else {
// action when permission denied
}
return;
}
}
}
MyActivity.cameraRequestCode is a static int, can be any unique int value.
In your adapter class
class Adapter extends RecyclerView.Adapter<Your adapter.MyViewHolder> implements ActivityCompat.OnRequestPermissionsResultCallback{`//enter code here`}
It will override the onRequestPermissionsResult
I have a same problem in RecylclerView.Adapter and I use this section in permission request method
private void requestCallPhonePerm() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
onItemCallListener.itemCallPhone(itemPhones);
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else {
((MainActivity)context).callPhone(itemPhones);
}
}
It's important to use (Activity)context in "requestPermissions" method to be invoked callback in container activity of your adapter
And in my MainActivity that contain recycler I use overrided request permission result normally.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if(grantResults.length>0
&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
new LoadContacts().execute();
}
break;
case MY_PERMISSIONS_REQUEST_CALL_PHONE:
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
callPhone(phones);
}else{
}
}
}
I solved this from custom class. My custom class is derived from AppCompatActivity. Also you need to pass Activity context to your custom class and do whatever you need with it.
public bool AreStorageAndCamPermissionsGranted(Activity context)
{
if (Build.VERSION.SdkInt >= Build.VERSION_CODES.M)
if (
context.CheckSelfPermission(Manifest.Permission.Camera)!= Android.Content.PM.Permission.Granted
|| context.CheckSelfPermission(Manifest.Permission.ReadExternalStorage) != Android.Content.PM.Permission.Granted
|| context.CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
{
ActivityCompat.RequestPermissions(context, new String[]
{
Manifest.Permission.Camera,
Manifest.Permission.ReadExternalStorage,
Manifest.Permission.WriteExternalStorage,
}, REQUEST_PERMISSION_CODE);
}
return true;
}
`

How to request permission to open camera hardware

I trying to develop an App that uses the Camera hardware in Android. While coding the following line
this.mCameraManager.openCamera(cameraIds[0], new CameraDevice.StateCallback() {...}
I was asked to explicitly check if the permission is available. when i added the permission check, Android added the following lines
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
and I override the follwoing method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
now, i do not know what to write inside the if-statement and the "onRequestPermissionsResult" mentioned above. your help is highly appreciated
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQ_ACCESS_FINE_LOCATION);
You have to show android permission dialog to users, after that you can catch users motions in onRequestPermissionsResult.
I think that you should look this website : https://developer.android.com/training/permissions/requesting.html
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_PERMISSIONS:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
// Open Camera
break;
}
}
Try this:
// The permission required by the application to work properly
protected static final String[] requiredPermissions;
private static final int PERMISSION_REQUEST = 0;
static {
List<String> perms = new ArrayList<>(Arrays.asList(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
));
requiredPermissions = perms.toArray(new String[perms.size()]);
}
Call verifyPermissions() method in onCreate():
private void verifyPermissions() {
if (!hasAllPermissions()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
this,
requiredPermissions,
PERMISSION_REQUEST
);
}
}
private boolean hasAllPermissions() {
// Check if we have all required permissions.
for (String perm : requiredPermissions) {
if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (!hasAllPermissions()) {
finish();
}
return;
}
}
}

Marshmallow won't show permission window

I have an app that needs write calendar now considered "critical" so I following the guidelines HERE I have added in Activity onCreate this cote
private static final int REQUEST_WRITE_CALENDAR = 1453;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_CALENDAR},
REQUEST_WRITE_CALENDAR);
}
But this doesn't show any dialog.
In addition seems I should ad also this code block to handle response
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your calendar.", Toast.LENGTH_LONG).show();
}
}
}
}
The Android Target SDK is 23 and is correct. So the cause of the problem is different from that proposed in possible duplicate question.
The logic for determining permission status can be simplified to this:
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_CALENDAR},
REQUEST_WRITE_CALENDAR);
}
Your Activity does not have to implement anything, overriding the onRequestPermissionsResult will be sufficient.
To the second part of the question:
You can override onRequestPermissionsResult in your activity or in your fragment. If you choose to do so in fragment instead of activity you should add something like this in your activity (in order to pass the callback to your fragment):
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (Fragment frag : getSupportFragmentManager().getFragments()) {
if (frag != null) {
frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

Categories

Resources