TakePhotoAsync相机未打开

时间:2019-03-28 17:02:52

标签: android xamarin xamarin.forms montemagno-media.plugin takephotoasync

我在网站上非常关注教程和答案,但没有成功。花很多时间。

使用Media.Plugin,方法TakePhotoAsync()无法打开相机(Genymotion 9.0 API-28 |设备三星j7 prime。android 8.0)。

PickPhotoAsync()很棒。

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.Pocidadao.fileprovider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
</provider>

file_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <external-path name="my_movies" path="Movies" />
  <external-path name="my_images" path="Android/data/com.companyname.Pocidadao/files/Pictures" /> 
</paths>

AssemblyInfo.cs

[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
[assembly: UsesFeature("android.hardware.camera", Required = false)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]

MainActivity.cs

protected override async void OnCreate(Bundle savedInstanceState)
{
    try
    {
...
        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        await CrossMedia.Current.Initialize();
        CrossCurrentActivity.Current.Init(this, savedInstanceState);
        UserDialogs.Init(this);
        LoadApplication(new App());
    }
    catch (Exception ex)
    {
        Console.WriteLine("EXCEPTION HERE => "+ex);

...

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

METHOD.XAML.CS

>> var文件中的问题=等待CrossMedia.Current.TakePhotoAsync(新的Plugin.Media.Abstractions.StoreCameraMediaOptions .. 但不是错误,异常等...

async void TakePhoto(object sender, EventArgs args)
        {
            try
            {
                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await DisplayAlert("Ops", ":( Nenhuma câmera detectada.", "OK");
                    return;
            }

            var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
            var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);

            if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted)
            {
                var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera, Permission.Storage });
                cameraStatus = results[Permission.Camera];
                storageStatus = results[Permission.Storage];
            }

            if (cameraStatus == PermissionStatus.Granted && storageStatus == PermissionStatus.Granted)
            {

        //===HERE IS THE PROBLEM, READ METHOD BUT NOT OPEN CAMERA! NOT ERRORS, NOT EXCEPTION, NOTHING===
                var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    SaveToAlbum = true,
                    //Directory = "Sample",
                    //Name = "test.jpg"
                });


                if (file == null)
                    return;

                await DisplayAlert("File Location", file.Path, "OK");

                if (MyImage.Source == null)
                {
                    Console.WriteLine("MyImage.Source == null ==> OK");
                }

                MyImage.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    file.Dispose();
                    return stream;
                });
            }
            else
            {
                await DisplayAlert("Permissions Denied", "Unable to take photos.", "OK");
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("EXCEPTION HERE =: "+e);
        }
    }

2 个答案:

答案 0 :(得分:1)

我测试了您的代码,此错误是由file_path.xml

引起的
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_movies" path="Movies" />
<external-path name="my_images" path="Android/data/com.companyname.Pocidadao/files/Pictures" /> 
</paths>

如果我将my_images的路径更改为 <external-files-path name="my_images" path="Pictures" />,您可以照常拍照

这是我的演示。

https://github.com/851265601/TakePhotoDemo

这是我的演示的GIF。

enter image description here

答案 1 :(得分:0)

对于我来说,我的清单中缺少这部分代码,请检查一下。

<application android:label="XXX.Android" android:name="android.support.multidex.MultiDexApplication">
    <provider android:name="androidx.core.content.FileProvider"
      android:authorities="${applicationId}.fileprovider"
      android:exported="false"
      android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
    </provider>
</application>