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

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)
}
}

Related

Android location permissions not requesting and automatically denied

The first few times I tried the code out, it prompted me each time requesting for the permissions but after a while, it would just go straight to my manual input page.
Also, I'm not sure if it would be relevant but my targetSDKVersion is 30.
Please and thank you for the help :)
I included these permissions in my AndroidManifext.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
The general flow of my code is that it'll check the permissions like so
private boolean checkPermissions() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
And then, if the permissions are not granted, it should request the user for their location calling requestPermissions()
private void requestPermissions() {
Log.d(TAG, "requestPermissions");
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION}, PERMISSION_ID);
}
And after that:
// If everything is alright then
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
//if user denies permission to use GPS services
//update UI accordingly for manual input
}
}
But it doesn't request, and I don't know why. I've read the documentation here https://developer.android.com/training/location/permissions, but I just don't get it :\
I've been searching for this for a long time. You first have to ask for basic location permissions, when those granted, then ask for background location permission. It will take the user to phone settings page to allow all the time.
private void LocationPermission() {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(MainActivity.this, R.string.permission_granted, Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, LOCATION_CODE2);
}else{
getLocation();
}
} else {
Toast.makeText(this, "Location access is required!", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == LOCATION_CODE2) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(MainActivity.this, R.string.permission_granted, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Location access granted!", Toast.LENGTH_SHORT).show();
getLocation();
} else {
Toast.makeText(this, "Location access is required!", Toast.LENGTH_SHORT).show();
}
}
}
Helloo~
I've removed the permission requests for Manifest.permission.ACCESS_BACKGROUND_LOCATION and it workds now :O!!
Thanks to Pawel for pointing it out :D

error permision ACCESS_FIND_LOCATION

I'm using permission ACCESS_FINE_LOCATION but when run.error:requires ACCESS_FINE_LOCATION permission
why?
thanks in advance.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION both permission required when to trying to get location
so add this both permission in manifest file as well as if you targeting android 6.0 and above than add this runtime permsiion like below code
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);
}
now handle permisiion result
#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 ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "location_permission_not_granted ", Toast.LENGTH_SHORT).show();
}
}
}
Did you write run time permissions in your code? As from Android 6.0, for every permission stated in manifest, must also be asked run time from user.
private void requestLocationPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);
}
}
Also handle user's response as well:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_CODE: {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
return;
}
}
}

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.

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!

Camera permission is not working on Marshmallow and above devices and crashes

Since I have made a flashlight application and it works properly on the device which have SDK 22 and below. But when I come to check on marshmallow and above devices, it doesn't run and crashes at the beginning only I asked for permission using following code but it doesn't seems to be working at all. here is my code for requesting permission of camera at run time. here is my code:
if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 5) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
}
else {
// Your app will not have this permission. Turn off all functions
// if permission not granted it will force close the app
}
}
I have tried in marshmallow, nougat devices but it doesnt ask for camera permission and i have to go through manually from setting-app-flashlight-permission-allow. can anyone help me please. Currently I am testing my app in Lineage os 7.1.1
You need to add the SDK 23 permission in manifest. add the below line in manifest then you will get runtime permission callback.
<uses-permission-sdk-23 android:name="android.permission.CAMERA"/>
Just you change only if condition your code is perfect like this,
if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
to
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if( ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
if(currentAPIVersion>= 23)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
Manifest.permission.CAMERA)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Camera Permission Necessary");
alertBuilder.setMessage("Camera permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
return false;
} else {
return true;
}
} else {
return true;
}
Use the below code and call the "requestPermission" method in onCreate of the Activity:
private static final int REQUEST_CODE_PERMISSION = 2;
List<String> mPermission=new ArrayList<String>();
public void requestPermission()
{
try {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= MockPackageManager.PERMISSION_GRANTED)
mPermission.add(Manifest.permission.CAMERA);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= MockPackageManager.PERMISSION_GRANTED
)
mPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE
);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= MockPackageManager.PERMISSION_GRANTED)
mPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
if(mPermission.size()>0)
{
String[] array = mPermission.toArray(new String[mPermission.size()]);
ActivityCompat.requestPermissions(this, array, REQUEST_CODE_PERMISSION);
// If any permission aboe not allowed by user, this condition will execute every tim, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
}
Overwrite the method "onRequestPermissionsResult":
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.e("Req Code", "" + requestCode);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length == mPermission.size()) {
for(int i=0;i<grantResults.length;i++)
{
if(grantResults[i] == MockPackageManager.PERMISSION_GRANTED)
{
//don't do anything....
}
else{
mPermission=new ArrayList<String>();
requestPermission();
break;
}
}
}
else{
Toast.makeText(this,"permition not granted",Toast.LENGTH_LONG).show();
mPermission=new ArrayList<String>();
requestPermission();
}
}
}
do this way:
if (ContextCompat.checkSelfPermission(UserProfileActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(UserProfileActivity.this, new String[]{Manifest.permission.CAMERA},
5);
} else {
//start flashlight
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case 5: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//start flashlight
Log.d("Permissions CAMERA", "Permission Granted: " + permissions[i]);
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
Log.d("Permissions CAMERA", "Permission Denied: " + permissions[i]);
}
}
break;
}
default: {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
} break;
}
}
I also had the same problem but managed to fixed it. Here's my case (I don't know if its the same as yours but it's worth a try)
So I have this two activities namely: MainActivity, and FlashlightActivity.
I used to ask for camera permission explicitly in FlaslightActivity just before I tap the switch button but I forgot that I was checking if a user's phone has a camera in the onCreate() method. while I was asking for permission onClick of the switch button of the flashlight, in which that was after I checked if a user's phone has a camera. So what I did was to ask for the permission in my MainActivity just before I start FlashlightActivity.
flashBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasPermission()){
Intent flashIntent = new Intent("FlashlightActivity");
startActivity(flashIntent);
}else{
requestPermission();
}
}
});
So basically ask for the permission before you call any Camera related stuffs

Categories

Resources