App starts twice in oncreate - android

I am using the following code to obtain read write permissions, however the problem is, by having this piece of code in oncreate, my app starts twice instead of once. How do I fix this?
// **check if app has permission 1**//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE }, 2909);
} else {
// continue with your code
}
} else {
// continue with your code
}
here is rest of the code which is outside oncreate-
// **check if app has permission 2**//
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "Granted");
} else {
Log.e("Permission", "Denied");
}
return;
}
}
}

have you tried to use this to check permission
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
this well return if permission is granted or revoked ...
refer to this tutorial Requesting Permissions at Run Time

for this particular example first you can check if permission is granted or not
checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
if result is false then request permission
edit
change if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
to
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) || checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE )
!= PackageManager.PERMISSION_GRANTED)))

Related

Android permissionCheck not working

AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Code :
button.setOnClickListener {
var permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
toast("success")
} else {
toast("fail")}}
Why does this return "fail" ?
For Android 6.0+ or targetSdk=23 you have to consider asking for run-time permissions. The permissions android.permission.ACCESS_FINE_LOCATION is considered dangerous so you have to ask for it at run-time. See Normal and Dangerous Permissions for an overview.
What you have to do is to ask it at run-time e.g.
from the developer guidelines
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Read more here at Requesting Permissions at Run Time
In this case you should request the permission like:ActivityCompat.requestPermissions(thisActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
and you should get an answer in onRequestPermissionsResult callback.
Then, if the user grant the permission, at the next time you will use the checkSelfPermission method you will get success.
For more details read this: https://developer.android.com/training/permissions/requesting.html
It seems you are using target sdk >=23 and run app on device with api level also >=23. So since api 23 there is new flow to recive permissions. Permissions are divided into two categories, normal and dangerous. Dangerous permissions should be asked in runtime like this:
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_LOCATION);
This will show system dialog for user:
So result of user's selections will be returned to public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
With request code that you passed in ActivityCompat.requestPermissions, in my case it is MY_PERMISSIONS_REQUEST_LOCATION
Permissions' names will be in String permissions[] and user's selections will be accordingly in int[] grantResults, with can be PackageManager.PERMISSION_GRANTED or PERMISSION_DENIED.
Also it's good to explain to user why you need that permission before asking it.
See more here:Requesting Permissions at Run Time
You can check Permission after/in Android 6.0
public class MainActivity extends AppCompatActivity {
private final int PERMISSIONS_CODE = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION,}, PERMISSIONS_CODE);
} else {
// You can do you operation directly. If you added permissions in AndroidManifest...
// Or visit following link to read about permission check.
// https://stackoverflow.com/questions/7203668/how-permission-can-be-checked-at-runtime-without-throwing-securityexception
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[grantResults.length-1] == PackageManager.PERMISSION_GRANTED) {
Log.d("permission", "accepted");
} else {
Log.d("permission", "denied");
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
}
Happy coding...
for Android 6.0 and your targetSdkVersion >=23 , you should ask permission at run time,I have two advise:
1、you can change your targetSdkVersion in model gradle file,eg:
targetSdkVersion=22
but,I don't recommend use this method.
2、this return 'fail' mean you don't have this permission,your should
consider if your have request but user refuse,in this your can show a dialog to tell use ,why you need this perssion,and then request the permession you want,you can use this code below:
private boolean check(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
//you have this permession
return true;
}else{
//don't hava permession ,you shoud check if you can request
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
//the use refuse you request this permission ,the system well't show request dialog,you shoul show a dialog tu explain why you need this permission
//and guide he go to system setting open this permission.
}else {
// you can request permission direct
//requestCode is a integer code,that you can use is in onRequestPermissionsResult
ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION, requestCode);
}
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//in this you can listen the request result
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
//user Agree permission
}else{
//user reject permission
}
}
I'm sorry,I only know java,so,this code is jave. hope this can help you to deal this problem.
Requesting permissions is too confusing for me, EasyPermissions solved all my problems
Manifest :
compile 'pub.devrel:easypermissions:0.4.2'
Code :
button.setOnClickListener {
if (EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
toast("yes !")
} else {
EasyPermissions.requestPermissions(this, getString(R.string.location_perm), 1, Manifest.permission.ACCESS_FINE_LOCATION )
}}
worked perfect first try
public static int CAMERA_PERMISSSION_CODE = 1;
public static int STORAGE_PERMISSSION_CODE = 2;
public static int FINE_LOCATION_PERMISSSION_CODE = 3;
public static int COARSE_LOCATION_PERMISSSION_CODE = 3;
public static int READ_PHONESTATE_PERMISSSION_CODE = 4;
private void askForunTimePermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(PermissionsActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSSION_CODE);
} else if (ContextCompat.checkSelfPermission(PermissionsActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSSION_CODE);
} else if (ContextCompat.checkSelfPermission(PermissionsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_PERMISSSION_CODE);
} else if (ContextCompat.checkSelfPermission(PermissionsActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, COARSE_LOCATION_PERMISSSION_CODE);
} else if (ContextCompat.checkSelfPermission(PermissionsActivity.this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, READ_PHONESTATE_PERMISSSION_CODE);
} else {
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
try {
if (requestCode == CAMERA_PERMISSSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
askForunTimePermissions();
} else {
askForunTimePermissions();
}
} else if (requestCode == STORAGE_PERMISSSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
askForunTimePermissions();
} else {
askForunTimePermissions();
}
} else if (requestCode == FINE_LOCATION_PERMISSSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
askForunTimePermissions();
} else {
askForunTimePermissions();
}
} else if (requestCode == COARSE_LOCATION_PERMISSSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
askForunTimePermissions();
} else {
askForunTimePermissions();
}
} else if (requestCode == READ_PHONESTATE_PERMISSSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
askForunTimePermissions();
} else {
askForunTimePermissions();
}
}
} catch (Exception e) {
Toast.makeText(PermissionsActivity.this, "No permission requests matched", Toast.LENGTH_SHORT).show();
}
}
//call this method where u want
askForunTimePermissions();
To check Location Permission via PermissionChecker.checkSelfPermission, you need to enable Location first. Otherwise PermissionChecker.checkSelfPermission will always return -2.

Android check camera permission in target sdk 22 or lower

I have my code like this to check camera permission.
if (Build.VERSION.SDK_INT >= 23) {
Log.e("Permission State",ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)+"");
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
showCameraActivityForResult(activity);
}else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, Constant.MY_PERMISSIONS_REQUEST_CAMERA);
}
}else{
showCameraActivityForResult(activity);
}
Problem is that I always have permission granted in 5.1 or lower. Other user also said here.
How can I know if my app's camera permission is granted?
In some device like samsung, user can disable camera permission from device setting and as a result, when user open my app and tap on camera, it always show blank. How can I detect whether user can use camera? (it need to be different from my code since it is not working.)
If you use AppCompatActivity, you can use checkSelfPermission to check if permission have been granted.
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) {
//Show permission dialog
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.CAMERA}, code);
}
}
On API 22 and below permissions are granted if specified in the manifest.
For API 23+ ContextCompat#checkSelfPermission could be of use. It "degrades" gracefully on earlier APIs and will tell you the permission is granted if it appears in the manifest. On API 23 and above it will actually check if it's granted.
It returns PackageManager.PERMISSION_GRANTED if the permission is granted.
call it in an Activity with Manifest.permission.CAMERA to avoid typos.
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA));
Try this,
private Context mContext=YourActivity.this;
private static final int REQUEST = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.CAMERA};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
showCameraActivityForResult(activity);
}
} else {
showCameraActivityForResult(activity);
}
get Permissions Result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showCameraActivityForResult(activity);
} else {
Toast.makeText(mContext, "The app was not allowed to write in your storage", Toast.LENGTH_LONG).show();
}
}
}
}
check permissions for marshmallow
private static boolean hasPermissions(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;
}
Manifest
<uses-permission android:name="android.permission.CAMERA" />
OR :
if (Build.VERSION.SDK_INT >= 23)
{
Log.e("Permission State",ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)+"");
// Here, thisActivity is the current activity
if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
{
showCameraActivityForResult(activity);
}
else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.CAMERA}, Constant.MY_PERMISSIONS_REQUEST_CAMERA);
}
}else{
showCameraActivityForResult(activity);
}
checkSelfPermission is available above sdk 23.
we can check the permission is available or not using package manager
public static Boolean checkpermissions(Activity activity) {
PackageManager mPackageManager = activity.getPackageManager();
int hasPermStorage = mPackageManager.checkPermission(android.Manifest.permission.CAMERA, activity.getPackageName());
if (hasPermStorage != PackageManager.PERMISSION_GRANTED) {
// do stuff
// Toast.makeText(getApplicationContext(), "No permission", Toast.LENGTH_LONG).show();
return false;
} else if (hasPermStorage == PackageManager.PERMISSION_GRANTED) {
// do stuff
// Toast.makeText(getApplicationContext(), "Has permission", Toast.LENGTH_LONG).show();
return true;
} else {
return false;
}

How to grant permission for the camera?

I just need a way to get permission for using the camera of the smartphone.
I wrote this code, but the permission request dialog doesn't appear.
in the onCreate:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// my code after granted permission
} else {
}
return;
}
}
}
requestPermissions() is not called because "ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)" is true
Step #1: Show some rationale (dialog, snackbar, something inline in your UI, whatever)
Step #2: When the user taps on something specific in that rationale UI (e.g., OK button), call requestPermissions()
Or, if you do not want to show rationale for why you are requesting the permission, do not call shouldShowRequestPermissionRationale().

Android API 23 Requesting Multiple Permissions

I am trying to request permissions on my Launcher Activity. For API < 23, it works perfect. However, when I test the app on a device running API 23, it says: "PostPaid Balance has stopped." I hit the "close App button," the app closes and immediately asks for one permission. I hit accept. Then I tap on the app icon to reopen and the same thing happens, except that now it asks for the next permission. Then I tap on the app icon and this time executes correctly.
It seems like it is asking for permissions one at a time. Any ideas on how to go about this?
// Below code is implemented on onCreate() of the launcher activity.
if (Build.VERSION.SDK_INT < 23) {
ActivityCompat.checkSelfPermission(this.getApplicationContext(), "android.permission.READ_SMS");
ActivityCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.READ_CALL_LOG);
ActivityCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
if ((ActivityCompat.checkSelfPermission(this, "android.permission.READ_SMS") != PackageManager.PERMISSION_GRANTED)) {
requestSmsPermission();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPhoneStatePermission();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestCallLogPermission();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((this.checkSelfPermission("android.permission.READ_SMS") != PackageManager.PERMISSION_GRANTED) &&
(this.checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) &&
(this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
this.requestPermissions(new String[]{"android.permission.READ_SMS", Manifest.permission_group.PHONE}, REQUEST_SMS);
}
}
To answer your question on how to request for multiple permissions in one go, add permissions to your array of strings. In this example, I want to request permissions for READ_PHONE_STATE and WRITE_EXTERNAL_STORAGE:
ArrayList<String> arrPerm = new ArrayList<>();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
arrPerm.add(Manifest.permission.READ_PHONE_STATE);
}
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
arrPerm.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if(!arrPerm.isEmpty()) {
String[] permissions = new String[arrPerm.size()];
permissions = arrPerm.toArray(permissions);
ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_REQUEST);
}
Now, check which permissions were granted:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0) {
for(int i = 0; i < grantResults.length; i++) {
String permission = permissions[i];
if(Manifest.permission.READ_PHONE_STATE.equals(permission)) {
if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// you now have permission
}
}
if(Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// you now have permission
}
}
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
break;
}
}
// other 'case' lines to check for other
// permissions this app might request
}

How get permission for camera in android.(Specifically Marshmallow)

Hey I am designing an app in android studio. In which i require permission of camera. I have included <uses-permission android:name="android.permission.CAMERA" />
in the the AndroidManifest.xml file. It is working properly in all versions of android except Marshmallow. How do I get camera permission by default? If not possible how do I ask it from user?
First check if the user has granted the permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
Then, you could use this to request to the user:
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
And in Marshmallow, it will appear in a dialog
You can try the following code to request camera permission in marshmallow. First check if the user grant the permission. If user has not granted the permission, then request the camera permission:
private static final int MY_CAMERA_REQUEST_CODE = 100;
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}
After requesting the permission, dialog will display to ask permission containing allow and deny options. After clicking action we can get result of the request with the following method:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
This works for me, the source is here
int MY_PERMISSIONS_REQUEST_CAMERA=0;
// Here, this is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA))
{
}
else
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA );
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
check using this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
and
I try to add following code:
private static final int MY_CAMERA_REQUEST_CODE = 100;
#RequiresApi(api = Build.VERSION_CODES.M)
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}
On onCreate Function and this following code:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
And this worked for me :)
One of the easiest way to take permission is to used the deterex library. like below
Implement the following library in your gradle.
implementation 'com.karumi:dexter:6.2.2'
after adding the library used this for permission like below
Dexter.withContext(this)
.withPermissions(
Manifest.permission.CAMERA
).withListener(new MultiplePermissionsListener() {
#Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
#Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/*
... */}
}).check();
Don't forget to add the user permission in your manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Requesting Permissions
In the following code, we will ask for camera permission:
in java
EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.
Installation
EasyPermissions is installed by adding the following dependency to your build.gradle file:
dependencies {
// For developers using AndroidX in their applications
implementation 'pub.devrel:easypermissions:3.0.0'
// For developers using the Android Support Library
implementation 'pub.devrel:easypermissions:2.0.1'
}
private void askAboutCamera(){
EasyPermissions.requestPermissions(
this,
"A partir deste ponto a permissão de câmera é necessária.",
CAMERA_REQUEST_CODE,
Manifest.permission.CAMERA );
}
click here for full source code and learn more.
Before get permission you can check api version,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 401);
}
}
else
{
// if version is below m then write code here,
}
Get the Result of the permission dialog,
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 401) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
} else if (requestCode == 402) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
private const val CAMERA_PERMISSION_REQUEST_CODE = 2323
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (checkSelfPermission(Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED)
{
requestPermissions(arrayOf(Manifest.permission.CAMERA),
CAMERA_PERMISSION_REQUEST_CODE)
}
}

Categories

Resources