I tried to make an app than can switch my camera flash on and off.
The code I have atm looks like this:
Camera flash;
Camera.Parameters params;
flash = Camera.open();
params = flash.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
flash.setParameters(params);
And in the manifest xml:
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal" />
<permission android:name="android.permission.CAMERA"> </permission>
Everytime I run the code, the app crashes at "flash = Camera.open();" with this error:
java.lang.RuntimeException: Fail to Connect to camera service
What am I doing wrong?
To access the device camera, you must declare the CAMERA permission in your Android Manifest like this,
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
You might have forgotten to call release in onDestroy
For example:
#Override
protected void onDestroy() {
if (mCamera != null) {
mCamera.release();
}
super.onDestroy();
}
Usually that problem is due to the missing camera request permission, as already said by other users.
But, just to register here another cause, if you try to open the camera using a cameraID that does not exist, you will receive that same error
java.lang.RuntimeException: Fail to Connect to camera service
You need to add the new request permission on android 6.x programmatically before.
private static final int MY_PERMISSIONS_REQUEST_CAMERA = 555;
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
} else {
IntentIntegrator.forSupportFragment(this).initiateScan();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
IntentIntegrator.forSupportFragment(this).initiateScan();
} else {
FragmentHelper.popFragment(getActivity(), null, null);
}
}
}
}
Related
I tried to access the camera from the phone, it worked 3 times, after the screen went black (Print below) in API 24, I tested it on a cell phone with API 22 and it worked, with the API 24 no, does anyone know how to solve it?
public class fotos extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView ivPhoto;
private Button btTakeaaPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fotos);
ivPhoto = findViewById(R.id.ivPhoto);
btTakeaaPhoto = findViewById(R.id.btTakeaPhoto);;
btTakeaaPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//config.showProgress(true, progressBar, context);
dispatchTakePictureIntent();
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ivPhoto.setImageBitmap(imageBitmap);
}
}
}
The screen stays like this for a few seconds and then the camera closes and returns to the activity.
Edit: The application does not stop working, it just opens the camera screen, turns black, and after a few seconds it closes, as I already said
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />
The problem is not the permissions, they have already been given, I already looked at the configurations to confirm. That's not the problem.
You might want to check several parts in your project.
1. in you AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />
check if you've already add such permission requests.
2. in your source code, for permission request from Android 6. You should have following code.
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
return;
}
for requestCameraPermission() function
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
you should ask that user to grant the permission and implement the callback function
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ErrorDialog.newInstance(getString(R.string.request_permission))
.show(getChildFragmentManager(), FRAGMENT_DIALOG);
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
After you granted the permission, open your camera and config the correct parameters. you can check the repo here https://github.com/wangchauyan/camera_sample.git, which I used to create my own camera application.
Hope that would be helpful.
I did it work, and do you know how? I rebooted the cell phone, do you know how I discovered it? I tried using the camera's function of WhastApp and showed me the message that it was not possible to access the camera at that moment, which was for me to reboot, so after that, it magically worked. WWWTTFFFF
I'm trying to start a ACTION_IMAGE_CAPTURE activity in order to take a picture in my app and I'm getting the error in the subject.
Stacktrace:
FATAL EXCEPTION: main
Process: il.ac.shenkar.david.todolistex2, PID: 3293
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity } from ProcessRecord{22b0eb2 3293:il.ac.shenkar.david.todolistex2/u0a126} (pid=3293, uid=10126)
with revoked permission android.permission.CAMERA
The camera permissions is added to the manifest.xml fie:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Here is the call to open the camera:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.statusgroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton rb = (RadioButton) findViewById(R.id.donestatusRBtn);
if(rb.isChecked())
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Remove this permission
<uses-permission android:name="android.permission.CAMERA"/>
I faced this error executing my app in android 7. After tests I noticed user permission wasn't in project A but it was in project B, that I only tested in android 5 devices. So I remove that permission in project B in order to run it on other device that targets android 7 and it finally could open.
In adittion I added the fileprovider code that Android suggests here https://developer.android.com/training/camera/photobasics.html
Hope this helps.
hi you can use these permission in your manifest file with other permission,
<uses-feature
android:name="android.hardware.camera.any"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
Now we have very sorted way for permission handling. So,here is the steps. I have added here for kotlin.
Step 1. Declare this as global variable or any where.
private val permissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
granted.entries.forEach {
when (it.value) {
true -> {
// Call whatever you want to do when someone allow the permission.
}
false -> {
showPermissionSettingsAlert(requireContext())
}
}
}
}
Step 2.
// You can put this line in constant.
val storagePermission = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE
)
// You can put this in AppUtil.
fun checkPermissionStorage(context: Context): Boolean {
val result =
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
return result == PackageManager.PERMISSION_GRANTED
}
// Put this where you need Permission check.
if (!checkPermissionStorage(requireContext())) {
permissions.launch(
storagePermission
)
} else {
// Permission is already added.
}
Step 3. Permission rejection Dialog. If you want you can use this.
fun showPermissionSettingsAlert(context: Context) {
val builder = AlertDialog.Builder(context)
builder.setTitle("Grant Permission")
builder.setMessage("You have rejected the Storage permission for the application. As it is absolutely necessary for the app to perform you need to enable it in the settings of your device. Please select \"Go to settings\" to go to application settings in your device.")
builder.setPositiveButton("Allow") { dialog, which ->
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts("package", context.packageName, null)
intent.data = uri
context.startActivity(intent)
}
builder.setNeutralButton("Deny") { dialog, which ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
Thankyou
hope this will help you (Y).
Here is how I solved mine:
First of all I think the issue arises when you try to use your device Camera on (SDK < 26) without FULL permissions.
Yes, even though you have already included this permission:
<uses-permission android:name="android.permission.CAMERA"/>
To solve this issue I changed that to this:
<uses-permission android:name="android.permission.CAMERA"
android:required="true"
android:requiredFeature="true"/>
This information from the Android Docs, might be really helpful
If your application uses, but does not require a camera in order to function, instead set android:required to false. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility to check for the availability of the camera at runtime by calling hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY). If a camera is not available, you should then disable your camera features.
In my case the problem was related to my emulator permissions ,
To fix the issue :
1- Go to Settings of your emulator.
2- Look for Apps and Notifications.
3- Click on Add Permission.
see the pic : https://i.stack.imgur.com/z4GfK.png
4- Select Camera of the list.
5- Look for your Application in the provided list.
6- Enable Camera.
see the pic : https://i.stack.imgur.com/dJ8wG.pngEnjoy
Now you can use your camera on your emulator :)
private String [] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_PHONE_STATE", "android.permission.SYSTEM_ALERT_WINDOW","android.permission.CAMERA"};
on your OnCreate add this:
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
As some have pointed out, one solution is removing the Camera Permission from AndroidManifest.xml, i.e., remove this line:
<uses-permission android:name="android.permission.CAMERA" />
However, that was not enough for me, as I needed the Camera Permission for something else in my app. So what worked for me was tagging that permission as not required, like this:
<uses-permission android:name="android.permission.CAMERA" android:required="false" />
short answer ...its looking for permissions , upon failing permissions it throws exception ; moreover in this case its looking for Two Permissions i.e. first Storage and second Camera.
long answer.....Give it the permissions write way to work on all Versions of Android.I am looping to get both permissions Storage and Camera, So that it will work with Intent.
maintain in AndroidManifest.xml
<uses-feature
android:name="android.hardware.camera.any"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
check or request permissions by
private void myStoragePermission() {
if (ContextCompat.checkSelfPermission(Activity_Scan_QR.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
myCameraPermission();
} else {
//changed here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
}
}
//+10 changed its sinature as Fragment; without it onRequestPermissionsResult won't bbe called
private void myCameraPermission() {
if (ContextCompat.checkSelfPermission(Activity_Scan_QR.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
takePicture();
} else {
//changed here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
}
}
add onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_WRITE_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
myStoragePermission();
} else {
showSnackbar(R.string.act_ScanQR_txt13, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
case REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
takePicture();
} else {
showSnackbar(R.string.act_ScanQR_txt14, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
in above code takePicture(); is where I call for intent (start intent) , upon getting both the Storage and Camera permissions.
Don't get confused by reading a lot on error ;)
For future references, if someone encounters the problem in flutter related android projects:
https://github.com/apptreesoftware/flutter_barcode_reader/issues/32#issuecomment-420516729
In case anyone else get's this issue, my problem was that the app wasn't requesting any permissions when I ran it. It seems xiaomi devices automatically deny permissions to apps installed through adb. I just enabled the permissions through settings and it worked.
In case you need to keep
<uses-permission android:name="android.permission.CAMERA" />
permission in manifest, just make sure it is granted before opening system camera.
In modern android, you can do that like this:
val cameraPermissionResult =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { permitted ->
if (permitted) {
openSystemCamera()
}
}
You can use cameraPermissionResult as follows:
cameraPermissionResult.launch(Manifest.permission.CAMERA)
If your app has already that permission granted it will just call openSystemCamera() without any user action required.
In other case permission dialog will be shown and system camera will be opened based on permission user chooses.
I'm quite late but please check this because there's always some update
As per official developer page - https://developer.android.com/training/camera/photobasics, you don't need to use uses-permission in Manifest.xml instead use uses-feature :
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
Notice - it's uses-feature, not uses-permission ,
Check properly, if you are using uses-permission and uses-feature both at the same, possibly you will the same crash (this note is most important then updated content from official page, because i used both of the params at the same time and faced this crash, also when i started working on camera module in my app, i don't know why i wasn't faced this issue but now app just started crashing suddenly)
more info about android:required from developer page :
If your application uses, but does not require a camera in order to function, instead set android:required to false. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility to check for the availability of the camera at runtime by calling hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY). If a camera is not available, you should then disable your camera features.
in your androidManifest, you have to add :
<uses-feature android:name="android.hardware.camera" />
here is an full Manifest example of android camera project
I add bluetooth to my app but am running into the following problem. When I do the code:
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
The error is on the following line:
if(!bluetoothAdapter.isEnabled())
Error:
Missing permissions required by BluetoothAdapter.isEnabled :android.permissions.BLUETOOTH
I added the following permissions to the android manifest file:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />
but am still getting the same issue. Do you know what I did wrong?
You only need <uses-permission> tag since you are using a permission. You don't need <permissions> tag since this is not your custom permission.
Maybe you have placed <uses-permission> tag in the wrong element in manifest, but I cannot say anything else with the information you provided
Since your bluetoothAdapter can be null, either add to second IF null pointer check, or add a RETURN in first IF
It is also nice to have <uses-feature> tag
Let's say you have a button and then you click on it, Bluetooth needs to turn on. Here's a quick example how you would do it for Android 6.0 and above.
First, declare this variable in your Activity/Fragment:
public static final int PERMISSION_ASK = 1001;
Now, let's say this buttons is going to enable the bluetooth.
setOnClickListener:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(isBluetoothPermissionGranted()) {
// app already has required permissions
// do some task here
} else {
// app does not have permission yet.
// ask for permissions
askForBluetoothPermissions();
}
} else {
// Android version below 6.0, no need to check or ask for permission
// do some task here
}
}
});
Checking if application already has the required permission:
#RequiresApi(api = Build.VERSION_CODES.M)
private boolean isBluetoothPermissionGranted() {
boolean granted = false;
int bluetoothGranted = checkSelfPermission(Manifest.permission.BLUETOOTH);
int bluetoothAdminGranted = checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN);
if(bluetoothGranted == PackageManager.PERMISSION_GRANTED &&
bluetoothAdminGranted == PackageManager.PERMISSION_GRANTED) {
granted = true;
}
return granted;
}
If required permission is not granted, here's how you would ask for it:
#RequiresApi(api = Build.VERSION_CODES.M)
private void askForBluetoothPermissions() {
String[] permissions = new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
};
requestPermissions(permissions, PERMISSION_ASK);
}
And finally, here's how you would confirm if the user granted you the permission(s) or not:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ASK:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// all requested permissions were granted
// perform your task here
} else {
// permissions not granted
// DO NOT PERFORM THE TASK, it will fail/crash
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
Hope this helps
For Android 6.0 and above you must add the following to manifest file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />
<permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
App crashes after running the program with failed to initialize
Vuforia with permission exception
Android version is <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
testing on device 4.1.1 (api level 16) with front camera only.
Permission included in manifest file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:glEsVersion="0x00020000" />
exception at SampleApplicationSession's InitVuforiaTask Task, value of Vuforia.init() returned is -1.
Not sure what I missed.
Library included are armaebi-v7a/libVuforia.so, android-support-v4, jpct_ae, Vuforia
I have faced the same problem. If you see the example comes with the compiledSdKversion 22 because in newer versions the user have to explicitly give the Camera permission. My project is working with API 25 by adding some code to my android application. In my case, I asked for the Camera Permission before opening the vuforia activity when an user clic a FloatingActionButton:
FloatingActionButton flb=(FloatingActionButton)findViewById(R.id.floatingActionButton2);
flb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
else
{
Intent myIntent = new Intent(MainActivity.this, VideoPlayback.class);
startActivity(myIntent);
}
}
});
The VideoPlayback is the activity that use AR from vuforia included in the advance examples. In this case you have to listen to an onRequestPermissionsResult because we have to check the user's answer.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// Begin monitoring for Aruba Beacon-based Campaign events
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Intent myIntent = new Intent(MainActivity.this, VideoPlayback.class);
startActivity(myIntent);
}
}
}
In the onRequestPermissionsResult we check if the answer was positive an if so we open the activity.
I hope it works for you too.
I'm trying to start a ACTION_IMAGE_CAPTURE activity in order to take a picture in my app and I'm getting the error in the subject.
Stacktrace:
FATAL EXCEPTION: main
Process: il.ac.shenkar.david.todolistex2, PID: 3293
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity } from ProcessRecord{22b0eb2 3293:il.ac.shenkar.david.todolistex2/u0a126} (pid=3293, uid=10126)
with revoked permission android.permission.CAMERA
The camera permissions is added to the manifest.xml fie:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Here is the call to open the camera:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.statusgroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton rb = (RadioButton) findViewById(R.id.donestatusRBtn);
if(rb.isChecked())
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Remove this permission
<uses-permission android:name="android.permission.CAMERA"/>
I faced this error executing my app in android 7. After tests I noticed user permission wasn't in project A but it was in project B, that I only tested in android 5 devices. So I remove that permission in project B in order to run it on other device that targets android 7 and it finally could open.
In adittion I added the fileprovider code that Android suggests here https://developer.android.com/training/camera/photobasics.html
Hope this helps.
hi you can use these permission in your manifest file with other permission,
<uses-feature
android:name="android.hardware.camera.any"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
Now we have very sorted way for permission handling. So,here is the steps. I have added here for kotlin.
Step 1. Declare this as global variable or any where.
private val permissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
granted.entries.forEach {
when (it.value) {
true -> {
// Call whatever you want to do when someone allow the permission.
}
false -> {
showPermissionSettingsAlert(requireContext())
}
}
}
}
Step 2.
// You can put this line in constant.
val storagePermission = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE
)
// You can put this in AppUtil.
fun checkPermissionStorage(context: Context): Boolean {
val result =
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
return result == PackageManager.PERMISSION_GRANTED
}
// Put this where you need Permission check.
if (!checkPermissionStorage(requireContext())) {
permissions.launch(
storagePermission
)
} else {
// Permission is already added.
}
Step 3. Permission rejection Dialog. If you want you can use this.
fun showPermissionSettingsAlert(context: Context) {
val builder = AlertDialog.Builder(context)
builder.setTitle("Grant Permission")
builder.setMessage("You have rejected the Storage permission for the application. As it is absolutely necessary for the app to perform you need to enable it in the settings of your device. Please select \"Go to settings\" to go to application settings in your device.")
builder.setPositiveButton("Allow") { dialog, which ->
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts("package", context.packageName, null)
intent.data = uri
context.startActivity(intent)
}
builder.setNeutralButton("Deny") { dialog, which ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
Thankyou
hope this will help you (Y).
Here is how I solved mine:
First of all I think the issue arises when you try to use your device Camera on (SDK < 26) without FULL permissions.
Yes, even though you have already included this permission:
<uses-permission android:name="android.permission.CAMERA"/>
To solve this issue I changed that to this:
<uses-permission android:name="android.permission.CAMERA"
android:required="true"
android:requiredFeature="true"/>
This information from the Android Docs, might be really helpful
If your application uses, but does not require a camera in order to function, instead set android:required to false. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility to check for the availability of the camera at runtime by calling hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY). If a camera is not available, you should then disable your camera features.
In my case the problem was related to my emulator permissions ,
To fix the issue :
1- Go to Settings of your emulator.
2- Look for Apps and Notifications.
3- Click on Add Permission.
see the pic : https://i.stack.imgur.com/z4GfK.png
4- Select Camera of the list.
5- Look for your Application in the provided list.
6- Enable Camera.
see the pic : https://i.stack.imgur.com/dJ8wG.pngEnjoy
Now you can use your camera on your emulator :)
private String [] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_PHONE_STATE", "android.permission.SYSTEM_ALERT_WINDOW","android.permission.CAMERA"};
on your OnCreate add this:
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
As some have pointed out, one solution is removing the Camera Permission from AndroidManifest.xml, i.e., remove this line:
<uses-permission android:name="android.permission.CAMERA" />
However, that was not enough for me, as I needed the Camera Permission for something else in my app. So what worked for me was tagging that permission as not required, like this:
<uses-permission android:name="android.permission.CAMERA" android:required="false" />
short answer ...its looking for permissions , upon failing permissions it throws exception ; moreover in this case its looking for Two Permissions i.e. first Storage and second Camera.
long answer.....Give it the permissions write way to work on all Versions of Android.I am looping to get both permissions Storage and Camera, So that it will work with Intent.
maintain in AndroidManifest.xml
<uses-feature
android:name="android.hardware.camera.any"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
check or request permissions by
private void myStoragePermission() {
if (ContextCompat.checkSelfPermission(Activity_Scan_QR.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
myCameraPermission();
} else {
//changed here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
}
}
//+10 changed its sinature as Fragment; without it onRequestPermissionsResult won't bbe called
private void myCameraPermission() {
if (ContextCompat.checkSelfPermission(Activity_Scan_QR.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
takePicture();
} else {
//changed here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
}
}
add onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_WRITE_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
myStoragePermission();
} else {
showSnackbar(R.string.act_ScanQR_txt13, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
case REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
takePicture();
} else {
showSnackbar(R.string.act_ScanQR_txt14, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
in above code takePicture(); is where I call for intent (start intent) , upon getting both the Storage and Camera permissions.
Don't get confused by reading a lot on error ;)
For future references, if someone encounters the problem in flutter related android projects:
https://github.com/apptreesoftware/flutter_barcode_reader/issues/32#issuecomment-420516729
In case anyone else get's this issue, my problem was that the app wasn't requesting any permissions when I ran it. It seems xiaomi devices automatically deny permissions to apps installed through adb. I just enabled the permissions through settings and it worked.
In case you need to keep
<uses-permission android:name="android.permission.CAMERA" />
permission in manifest, just make sure it is granted before opening system camera.
In modern android, you can do that like this:
val cameraPermissionResult =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { permitted ->
if (permitted) {
openSystemCamera()
}
}
You can use cameraPermissionResult as follows:
cameraPermissionResult.launch(Manifest.permission.CAMERA)
If your app has already that permission granted it will just call openSystemCamera() without any user action required.
In other case permission dialog will be shown and system camera will be opened based on permission user chooses.
I'm quite late but please check this because there's always some update
As per official developer page - https://developer.android.com/training/camera/photobasics, you don't need to use uses-permission in Manifest.xml instead use uses-feature :
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
Notice - it's uses-feature, not uses-permission ,
Check properly, if you are using uses-permission and uses-feature both at the same, possibly you will the same crash (this note is most important then updated content from official page, because i used both of the params at the same time and faced this crash, also when i started working on camera module in my app, i don't know why i wasn't faced this issue but now app just started crashing suddenly)
more info about android:required from developer page :
If your application uses, but does not require a camera in order to function, instead set android:required to false. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility to check for the availability of the camera at runtime by calling hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY). If a camera is not available, you should then disable your camera features.
in your androidManifest, you have to add :
<uses-feature android:name="android.hardware.camera" />
here is an full Manifest example of android camera project