Oll*_*lie 3 android webview xamarin xamarin.forms
我正在尝试在 xamarin 表单应用程序中启用 webview 以获取 android 设备的当前 GPS 坐标。当前,当在手机或笔记本电脑上的 chrome 浏览器中打开时,webview/网站将返回 GPS 坐标,但在应用程序中不会。试图让这个工作尽可能简单,并在之后扩展它。
到目前为止的代码:XAML 页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="UITrial.Page2"
BackgroundColor = "#f0f0ea">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
<WebView Source="https://danu6.it.nuigalway.ie/OliverInternetProgramming/project/Loginproject.html" />
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
HTML页面:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当前,当在手机或笔记本电脑上的 chrome 浏览器中打开时,webview/网站将返回 GPS 坐标,但在应用程序中不会。
您需要使用自定义WebChromeClient为WebView在Droid的项目。请参考Android WebView 地理定位。
在 Xamarin.Forms 中,您可以按照以下步骤完成此操作:
在 PCL 项目中为 WebView 创建自定义控件:
public class GeoWebView:WebView
{
}
Run Code Online (Sandbox Code Playgroud)
并在 Xaml 中使用它:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:WebViewFormsDemo"
x:Class="WebViewFormsDemo.MainPage">
<local:GeoWebView
Source="https://danu6.it.nuigalway.ie/OliverInternetProgramming/project/Loginproject.html"></local:GeoWebView>
Run Code Online (Sandbox Code Playgroud)
GeoWebView在 Droid 项目中创建一个自定义渲染器,如下所示:
[assembly:ExportRenderer(typeof(GeoWebView),typeof(GeoWebViewRenderer))]
namespace WebViewFormsDemo.Droid
{
public class GeoWebViewRenderer:WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Settings.JavaScriptEnabled = true;
Control.SetWebChromeClient(new MyWebClient());
}
}
public class MyWebClient : WebChromeClient
{
public override void OnGeolocationPermissionsShowPrompt(string origin, GeolocationPermissions.ICallback callback)
{
callback.Invoke(origin, true, false);
}
}
}
Run Code Online (Sandbox Code Playgroud)添加权限AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)然后您将在 webview 中正确获取您的位置。
| 归档时间: |
|
| 查看次数: |
2858 次 |
| 最近记录: |