Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Xamarin - Requesting camera permissions in WebView

I want to make a container-app for my web application, and I decided to do so in Xamarin because the rest of the project is also .NET.

Initially I downloaded and setup the project from Xamarin Sample Pages: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=windows

I simply changed a few variables in WebPage.cs: https://github.com/xamarin/xamarin-forms-samples/blob/master/WorkingWithWebview/WorkingWithWebview/WebPage.cs

using Xamarin.Forms;

namespace WorkingWithWebview
{
    public class WebPage : ContentPage
    {
        public WebPage()
        {
            var browser = new WebView();
            browser.Source = "https://xamarin.swappsdev.net";
            Content = browser;
        }
    }
}

Secondly I updated App.cs to suit my needs: https://github.com/xamarin/xamarin-forms-samples/blob/master/WorkingWithWebview/WorkingWithWebview/App.

using Xamarin.Forms;

namespace WorkingWithWebview
{
    public class App : Application
    {
        public App ()
        {
            MainPage = new WebPage();
        }
    }
}

And boom! I had an app.

Then came the real struggle. In the web application I can – when opening the site (https://xamarin.swappsdev.net) in the browser – click on a button which requests permissions from the device and then display the camera feed in the same window.

When doing the same action in the app nothing happens.

I then started googling for an answer and really didn’t find a lot. And the answers I found seems to be of an older version of Xamarin (?), since I wasn’t able to compare the files and structure in the answer compared to the one of the Xamarin Sample Page. https://stackoverflow.com/a/50560855

I tried implementing the answer from Robbit here. After a long struggle I managed to compile it and install it on my device but it doesn't actually ask for permissions.

I am at a loss and could need some help/guidance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated:

In my previous answer, it shows how to add camera permission on webview.

The link you provided, it works now. https://xamarin.swappsdev.net/ It seems to provide a camera preview function. It need to check permissions on API 23+.

On Xamarin.Forms, you could use Permissions Plugin. https://github.com/jamesmontemagno/PermissionsPlugin

First, add the camera permission in Android Manifest. Your Project.Android> Properties> Android Manifest> Required permissions> Camera. After that, it would generate the user permission in AndroidManifest.xml.

  <uses-permission android:name="android.permission.CAMERA" />

Create a Utils.cs.

public static class Utils
{
    public static async Task<PermissionStatus> CheckPermissions(Permission permission)
    {
        var permissionStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
        bool request = false;
        if (permissionStatus == PermissionStatus.Denied)
        {
            if (Device.RuntimePlatform == Device.iOS)
            {

                var title = $"{permission} Permission";
                var question = $"To use this plugin the {permission} permission is required. Please go into Settings and turn on {permission} for the app.";
                var positive = "Settings";
                var negative = "Maybe Later";
                var task = Application.Current?.MainPage?.DisplayAlert(title, question, positive, negative);
                if (task == null)
                    return permissionStatus;

                var result = await task;
                if (result)
                {
                    CrossPermissions.Current.OpenAppSettings();
                }

                return permissionStatus;
            }

            request = true;

        }

        if (request || permissionStatus != PermissionStatus.Granted)
        {
            var newStatus = await CrossPermissions.Current.RequestPermissionsAsync(permission);

            if (!newStatus.ContainsKey(permission))
            {
                return permissionStatus;
            }

            permissionStatus = newStatus[permission];

            if (newStatus[permission] != PermissionStatus.Granted)
            {
                permissionStatus = newStatus[permission];
                var title = $"{permission} Permission";
                var question = $"To use the plugin the {permission} permission is required.";
                var positive = "Settings";
                var negative = "Maybe Later";
                var task = Application.Current?.MainPage?.DisplayAlert(title, question, positive, negative);
                if (task == null)
                    return permissionStatus;

                var result = await task;
                if (result)
                {
                    CrossPermissions.Current.OpenAppSettings();
                }
                return permissionStatus;
            }
        }

        return permissionStatus;
    }
}

In MainActivity.cs, add the code in OnCreate method.

 Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);

OnRequestPermissionsResult is needed in MainActivity.cs.

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

And then impletement it.

private async void _button_Clicked(object sender, EventArgs e)
    {
        webView.Source = "https://xamarin.swappsdev.net/";//"https://test.webrtc.org/";

        var status = PermissionStatus.Unknown;

        status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);

        if (status != PermissionStatus.Granted)
        {

            status = await Utils.CheckPermissions(Permission.Camera);
        }

    }

enter image description here

I have upload on my GitHub. Check the folder. Test/CameraRuntimePermission_WebView/RuntimePermission

https://github.com/WendyZang/Test.git

Edit:

If you do not want to call this in button click event, you could delete the button in MainPage.xaml.

MainPage.xaml.cs

 public MainPage()
    {
        InitializeComponent();
        webView.Source = "https://xamarin.swappsdev.net/";
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        RunTimePermission();
    }

    public async void RunTimePermission()
    {
        var status = PermissionStatus.Unknown;

        status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);

        if (status != PermissionStatus.Granted)
        {

            status = await Utils.CheckPermissions(Permission.Camera);
        }

    }

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...