Forum Xamarin.Forms

Cannot Access Camera Permission

Hi Having a problem while trying to take a image using the camera. Whenever i deploy a fresh install of the app. Open the app. Try to take a photo the permission dialog opens it asks for

"Allow to access photos, media and files" but there is no camera

image

I have the camera permission in the Android Manifest

I also have

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

in the MainActivity Class

the code thats taking the photo

private async void TakePhotoIDImage(object sender, EventArgs e)
{

        //var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
        //if (status == PermissionStatus.Granted)
        //{


        //}


        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await DisplayAlert("No Camera", ":( No camera available.", "OK");
            return;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            PhotoSize = PhotoSize.Medium,

        });

        if (file == null)
            return;


        using (var memoryStream = new MemoryStream())
        {
            file.GetStream().CopyTo(memoryStream);
            var myfile = memoryStream.ToArray();
            mysfile = myfile;
        }

        PhotoIDImage.Source = ImageSource.FromFile(file.Path);
    }

The app always crashes then i need to goto the phones settings -> app -> and manually set the camera permission to true before i can start testing the app which is obviously not the right way.

I've had it working on another app and comparing the settings they are exactly the same and also using on the same device.

I have also set the Compile and Target Android to API Level 23 but still no go.

always getting a permission error in the output. The error on the output window is

Does not have storage permission granted, requesting.

Java.Lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3 cmp=com.google.android.GoogleCamera/com.android.camera.activity.CaptureActivity clip={text/uri-list U:file:///storage/emulated/0/Android/data/SavR.SavR/files/Pictures/IMG_20170628_111109.jpg} (has extras) } from ProcessRecord{c28c0d6 28331:SavR.SavR/u0a245} (pid=28331, uid=10245) with revoked permission android.permission.CAMERA

any thoughts ??

Best Answer

Answers

  • CostasAletrariCostasAletrari USMember ✭✭

    fixed, HAD to use @JamesMontemagno permissions, lots of examples using Location, just changing location to Camera and sorted...

    private async void TakePhotoIDImage(object sender, EventArgs e)
    {

            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera))
                    {
                        await DisplayAlert("Camera Permission", "Allow SavR to access your camera", "OK");
                    }
    
                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera });
                    status = results[Permission.Camera];
                }
    
                if (status == PermissionStatus.Granted)
                {
    
                    await CrossMedia.Current.Initialize();
    
                    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                    {
                        await DisplayAlert("No Camera", ":( No camera available.", "OK");
                        return;
                    }
    
                    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                    {
                        PhotoSize = PhotoSize.Medium,
    
                    });
    
                    if (file == null)
                        return;
    
    
                    using (var memoryStream = new MemoryStream())
                    {
                        file.GetStream().CopyTo(memoryStream);
                        var myfile = memoryStream.ToArray();
                        mysfile = myfile;
                    }
    
                    PhotoIDImage.Source = ImageSource.FromFile(file.Path);
    
    
                }
                else if (status != PermissionStatus.Unknown)
                {
                    await DisplayAlert("Camera Denied", "Can not continue, try again.", "OK");
                }
            }
            catch (Exception ex)
            {
    
                await DisplayAlert("Error", "Camera Not Available", "OK");
            }
    
        }
    
  • CostasAletrariCostasAletrari USMember ✭✭
    Ahh ha. Thank you for that @JamesMontemagno
  • VinciusdaCruzMaiaVinciusdaCruzMaia BRMember ✭✭

    @JamesMontemagno I had the same issue. I not added Camera permission manually, but this exception occurs.

  • RenAlbert.8724RenAlbert.8724 CHMember ✭✭

    @JamesMontemagno said:
    The media plugin doesn't need the camera permission. If you add it manually then you need to request a permission. However I add all the permissions you need for the plugin. If you add the camera permission to the manifest then you need to check for it.

    iOs and UWP work properly. Android is exixtng a big descriton disaster

    The WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE permissions I alreads used in the datase these permission.
    That is no master discription. If you you do like hat: 4.1.05

    Media Plugin for Xamarin & Windows

    Find the latest at: https://github.com/jamesmontemagno/MediaPlugin

    Additional Required Setup (Please Read!)

    Android

    In your BaseActivity or MainActivity (for Xamarin.Forms) add this code:

    Add to Activity:

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
    {
    Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    The WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE permissions are required, but the library will automatically add this for you. Additionally, if your users are running Marshmallow the Plugin will automatically prompt them for runtime permissions.

    Additionally, the following has been added for you:
    [assembly: UsesFeature("android.hardware.camera", Required = false)]
    [assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]

    You must also add a few additional configuration files to adhere to the new strict mode:

    1.) Add the following to your AndroidManifest.xml inside the tags:



    2.) Add a new folder called xml into your Resources folder and add a new XML file called file_paths.xml

    Add the following code:

    <?xml version="1.0" encoding="utf-8"?>



    You can read more at: https://developer.android.com/training/camera/photobasics.html

    Android Current Activity Setup

    This plugin uses the Current Activity Plugin to get access to the current Android Activity. Be sure to complete the full setup if a MainApplication.cs file was not automatically added to your application. Please fully read through the Current Activity Plugin Documentation. At an absolute minimum you must set the following in your Activity's OnCreate method:

    CrossCurrentActivity.Current.Init(this, bundle);
    

    It is highly recommended that you use a custom Application that are outlined in the Current Activity Plugin Documentation](https://github.com/jamesmontemagno/CurrentActivityPlugin/blob/master/README.md)

    iOS

    Your app is required to have keys in your Info.plist for NSCameraUsageDescription and NSPhotoLibraryUsageDescription in order to access the device's camera and photo/video library. If you are using the Video capabilities of the library then you must also add NSMicrophoneUsageDescription. The string that you provide for each of these keys will be displayed to the user when they are prompted to provide permission to access these device features. You can read me here: https://blog.xamarin.com/new-ios-10-privacy-permission-settings/

    Such as:
    NSCameraUsageDescription
    This app needs access to the camera to take photos.
    NSPhotoLibraryUsageDescription
    This app needs access to photos.
    NSMicrophoneUsageDescription
    This app needs access to microphone.
    NSPhotoLibraryAddUsageDescription
    This app needs access to the photo gallery.

    UWP

    Set Webcam permission.

    Tizen

    Please add the following Privileges in tizen-manifest.xml file

    http://tizen.org/privilege/appmanager.launch
    http://tizen.org/privilege/mediastorage

    See below for additional instructions.
    https://developer.tizen.org/development/visual-studio-tools-tizen/tools/tizen-manifest-editor#privileges
    Regards René

Sign In or Register to comment.