My application only shows permission dialog only first time after app has been installed. If I close it and open again, it doesn't show request window. Even if I manually disable location permission or request permission window on clickEvent it doesnt work.
checkPermission:
private fun checkPermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//permission not granted
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
//show an explanation to the user
} else {
//request the permission
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
ACCESS_COARSE_LOCATION_CODE)
}
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
ACCESS_COARSE_LOCATION_CODE)
}
}
onRequestPermissionsResult:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
ACCESS_COARSE_LOCATION_CODE -> {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//granted
} else {
//denied
}
return
}
}
}
I call checkPermission function on onStart and when I click icon.
you left shouldShowRequestPermissionRationale part empty so it is not requesting permission second time . In it show an alert dialog why you need permission and when user clicks Ok ask for permission again . As an alternate you can ask permission again directly.
private fun checkPermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//permission not granted
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
ACCESS_COARSE_LOCATION_CODE)
} else {
//request the permission
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
ACCESS_COARSE_LOCATION_CODE)
}
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
ACCESS_COARSE_LOCATION_CODE)
}
}
You are not handling the deny and dont ask again cases properly , I would suggest you to use this library for simplicity . you will get all call backs at single place
Permissions.check(this, Manifest.permission.ACCESS_COARSE_LOCATION, null, new PermissionHandler() {
#Override
public void onGranted() {
// do your task.
}
});
when the user accepts your permission it accepts it permanently (unless the user remove it) check permission shows only when the permission is not granted yet. when the user clear data or uncheck the permission through setings->app settings-> chosen app->permisson.
private fun checkAndRequestPermissions(): Boolean {
val permissionContact = ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_CONTACTS)
val permissionPhoneState = ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_PHONE_STATE)
val permissionCamera = ContextCompat.checkSelfPermission(activity,
Manifest.permission.CAMERA)
val permissionWriteExternal = ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
val locationPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
val listPermissionsNeeded = java.util.ArrayList<String>()
when {
locationPermission != PackageManager.PERMISSION_GRANTED -> listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION)
}
when {
permissionContact != PackageManager.PERMISSION_GRANTED -> listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS)
}
when {
permissionPhoneState != PackageManager.PERMISSION_GRANTED -> listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE)
}
when {
permissionCamera != PackageManager.PERMISSION_GRANTED -> listPermissionsNeeded.add(Manifest.permission.CAMERA)
}
when {
permissionWriteExternal != PackageManager.PERMISSION_GRANTED -> listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
when {
!listPermissionsNeeded.isEmpty() -> ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toTypedArray(), REQUEST_ID_MULTIPLE_PERMISSIONS)
}
return true
}
Related
I know there are many questions answered regarding checking and requesting permission and handling their response and I am clear on that. But what I bit confuse about is if we are checking for same permission for two different things, how do we continue task after permission is granted?
For example,I have recycleView and in my adapter I have code for two buttons, one would save file and another one would save and open activity to share that file with other app.
MyRecycleAdapter {
Context context:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
have permission
save file to disk
} else {
requestPermission
save file to disk
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
have permission
save file to disk
open share activity using (context)
} else {
requestPermission
save file to disk
open share activity using (context)
}
}
});
}
Use different request codes to control what happens after permission is granted:
final int SAVE = 1;
final int SAVE_AND_SHARE = 2;
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
},
[either SAVE or SAVE_AND_SHARE]);
} else {
//permission is already granted, continue
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == SAVE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
//save
} else {
//permission was denied
}
} else if (requestCode == SAVE_AND_SHARE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
//save and share
} else {
//permission was denied
}
}
}
Just for the sake of completion. Requesting permissions has been simplified lately in the API. Here's how I check for a permission before doing some action:
private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Permission callback
val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
// Yay, permission was granted
doSomething()
}
else {
// Boo, permission was refused
Snackbar.make(root,"Wut ?! We need your permission!", Snackbar.LENGTH_LONG).show()
}
}
}
private fun checkLocationPermissionAndDoSomething() {
// Do we have the permission ?
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission is not granted. Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
// Explanation is needed. Show dialog
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Please")
builder.setMessage("We need to use your location because bla blah bla.")
builder.setPositiveButton(android.R.string.ok) { _, _ ->
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
builder.show()
}
else {
// No explanation needed, we can request the permission.
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
} else {
// Permission has already been granted
doSomething()
}
}
When multiple permissions are needed just use ActivityResultContracts.RequestMultiplePermissions and use an array of permissions
I'm developing an android app and i have problems with the camera permission.
On click of a button i call this
if (android.os.Build.VERSION.SDK_INT > 23) {
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);
}
} else {
BarCodeReaderActivity.startActivity(this, REQUEST_CODE_BAR_CODE, mStatus);
}
}else{
if (cameraAvailable)
BarCodeReaderActivity.startActivity(this, REQUEST_CODE_BAR_CODE, mStatus);
else {
Toast.makeText(this, KanbanBoxSettings.getInstance(this).getTranslationString(Strings.message_camera_not_available), Toast.LENGTH_LONG).show();
}
}
When i look on
Settings > Apps > "Your app" > Permissions i see that the app has the camera permission so why is the camera still unavailable?
I don't know if this errorlog is usefull but here is what i get:
E/StopWatchTimer: [LOG_ERR]StopWatchTimerStart : 63 - StopWatchTimer have already start!
Call this method before executing your camera code.
public void checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
// You don't have the permission you need to request it
ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_CODE_LOCATION);
} else {
// You have the permission.
setUserLocation();
}
}
Then, Override onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
setUserLocation();
} else {
toast(getApplicationContext(),"You have cancelled location accessed request");
currentLoaction.setImageDrawable(getResources().getDrawable(R.drawable.location));
}
}
}
Now call your camera method. If this is not working then post your camera calling code.
I have made an app that tracks call log in background using ContentObserver and service(runs in foreground).
Manifest.permission.CALL_PHONE
This is the permission i am checking for
if (CallTrackingHelper.isCallPermissionEnabled(appContext)) {
val task = OneoffTask.Builder()
.setService(CallLogService::class.java)
.setExecutionWindow(0, 6)
.setTag("call-track")
.setRequiredNetwork(Task.NETWORK_STATE_ANY)
.setRequiresCharging(false)
.setUpdateCurrent(true)
.build()
val mGcmNetworkManager = GcmNetworkManager.getInstance(appContext)
mGcmNetworkManager.schedule(task)
}
i start a gcmtaskservice that uploads call-log to server
override fun onRunTask(p0: TaskParams?): Int {
val callLogs = CallTrackingHelper.getCallLog(lastSyncedIndex, this)
//
}
in service i fetch contact
fun getCallLog(id: Long, service: CallLogService): ArrayList<CallLogModel> {
val callLogList = ArrayList<CallLogModel>()
if (!isCallPermissionEnabled(service)) {
return callLogList
}
var mCursor: Cursor? = null
try {
val args = arrayOf(id.toString())
if (id != 0L) {
mCursor = UCApplication
.getInstance()
.applicationContext
.contentResolver
.query(
CallLog.Calls.CONTENT_URI,
null,
"_id > ? ",
args,
null
)
} else {
mCursor = UCApplication
.getInstance()
.applicationContext
.contentResolver
.query(
CallLog.Calls.CONTENT_URI,
null,
null,
null,
CallLog.Calls._ID + " DESC" + " LIMIT 200 "
)
}
} catch (e: SecurityException) {
//
}
//
return callLogList
}
fun isCallPermissionEnabled(context: Context?): Boolean {
if (context == null || ContextCompat.checkSelfPermission(context, PERMISSIONS)
!= PackageManager.PERMISSION_GRANTED) {
return false
}
return true
}
Still i am getting lot of securityException so I have to add try and catch
You need to get run time permission in 6.0 > devices
get runtime permission like this:
final String[] NECESSARY_PERMISSIONS = new String[] {Manifest.permission.GET_ACCOUNTS };
if (ContextCompat.checkSelfPermission(DialerHomeActivity.this,
Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
//Permission is granted
} else {
//ask for permission
ActivityCompat.requestPermissions(
DialerHomeActivity.this,
NECESSARY_PERMISSIONS, 123);
}
Add this to your manifest.xml above <appication> tag:
<uses-permission android:name="android.permission.READ_CALL_LOG"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"></uses-permission>
you can read more at : here
Issue was that if user already has an app without
<uses-permission android:name="android.permission.READ_CALL_LOG"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"></uses-permission>
in manifest and gives call permission or phone permission , after update if these are added in update call/phone permission is still their but call log permission is not so you need to ask again.
Fresh install was working fine for me
Have you requested permissions on runtime?
// 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.
}
}
Check this:
https://developer.android.com/training/permissions/requesting.html
I was facing the same problem. Use this code for run time permission:
private static final int PHONE_LOG = 1;
private void checkCallLogPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG},PHONE_LOG);
return;
}
}
You can access all contact log for your mobile with this code
private static final int PHONE_LOG_PERMISSION= 1;
private void checkCallLogPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG},PHONE_LOG_PERMISSION);
return;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PHONE_LOG_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
In onCreate()of my activity I check for permissions.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CHECK_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
}
For every permission,in its callback method I perform certain tasks.So I cannot ask the permissions in array like
String[] permissions { };
as it will provide me only one call back for all permissions.I perform tasks in every callback in following way.
case ConstantClass.READ_PERMISSION:
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
doSomething();
Toast.makeText(MainActivity.this, getResources().getString(R.string.Cannot_Vibrate_Phone), Toast.LENGTH_LONG).show();
}
break;
case ConstantClass.CALL_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dialPhoneNumber();
} else {
Toast.makeText(MainActivity.this, getString(R.string.permission_access_call), Toast.LENGTH_LONG).show();
}
break;
If I ask these permissions one after other in onCreate(). Only the first permission is displayed.So I get only one call back working. So how to achieve the scenario that for every single permission I get a separate call back and call some functions in them.
Thank you :)
Check this Demo Code
Ask next permission in response of first permission reject/grant in
onRequestPermissionsResult()
public class MainActivity extends Activity {
private Context context;
private static final int REQUEST_RUNTIME_PERMISSION_1 = 111;
private static final int REQUEST_RUNTIME_PERMISSION_2 = 222;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
if (CheckPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// you have permission go ahead
} else {
// you do not have permission go request runtime permissions
RequestPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION_1);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions,
int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION_1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead ask next permission and get separate callback
RequestPermission(MainActivity.this, Manifest.permission.CAMERA, REQUEST_RUNTIME_PERMISSION_2);
} else {
// you do not have permission show toast.
/*check your logic ask again*/
//RequestPermission(MainActivity.this, Manifest.permission.CAMERA, REQUEST_RUNTIME_PERMISSION_2);
}
return;
}
case REQUEST_RUNTIME_PERMISSION_2: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have 2nd permission go ahead
} else {
// you do not have 2nd permission show toast.
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
You can ask the next permission in onRequestPermission to show permission request one after another. You can examine the below code and get the idea. In onRequestPermissionResult method:
case ConstantClass.READ_PERMISSION:
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
doSomething();
Toast.makeText(MainActivity.this, getResources().getString(R.string.Cannot_Vibrate_Phone), Toast.LENGTH_LONG).show();
}
// Ask for Camera permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHECK_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
break;
Hope this helps.
String permissions[] = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
&&ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&&ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
ActivityCompat.requestPermissions(this, permissions, ALL_REQUEST_CODE);
}
else if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&&ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {permissions[1], permissions[2], permissions[3]}, ALL_REQUEST_CODE);
}
else if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {permissions[2], permissions[3]}, ALL_REQUEST_CODE);
}
This is the best way to get permissions
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;
}