Reputation: 1849
My cross platform mobile app is taking photo with this codes
public void TakePhoto()
{
Context context = MainActivity.Instance;
MainActivity activity = (MainActivity)context;
Intent intent = new Intent(MediaStore.ActionImageCapture);
AppCamera._file = new Java.IO.File(AppCamera._dir, String.Format("Photo_{0}.jpg", DateTime.Now.ToString("ddmmyyhhmmss")));
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(AppCamera._file));
activity.StartActivityForResult(intent, 1);
}
I have the app on Android version 4.4 to 7.0 platforms and it works fine. but it is not working on a google pixel phone which Android version is 8.1.
Note: Calling this function using dependency service.
Xamarin.Forms.DependencyService.Register<ICameraProvider>();
DependencyService.Get<ICameraProvider>().TakePhoto()
I am using Visual Studio 2017, Xamarin Forms. and my project build properties platform target is Latest Platform Android 8.1(Oreo).
Any idea what the problem is ?
Upvotes: 1
Views: 1870
Reputation: 2168
Xamarin forms Can't Access Camera
As Jesus Angulo and SushiHangover said, the permission need request the user to approve at runtime on Android 6.0 and higher. This is official documentation for requesting runtime permissions. You could also refer to this blog and this sample for request runtime permission in xamarin.
Here is a simple demo:
public void TakePhoto()
{
if (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.Camera) != (int)Permission.Granted)
{
var requiredPermissions = new String[] { Manifest.Permission.Camera };
var activity = Xamarin.Forms.Forms.Context as Activity;
ActivityCompat.RequestPermissions(activity, requiredPermissions, 100);
}
while (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.Camera) != (int)Permission.Granted)
{
//waiting user permission
}
//Other code
//...
//...
}
And you also need set permission in AndroidManifest.xml or it will automatically be denied.
<uses-permission android:name="android.permission.CAMERA" />
Upvotes: 1