Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Last active March 30, 2021 20:51
Show Gist options
  • Save Cheesebaron/ad84740c9bffa7e255c8 to your computer and use it in GitHub Desktop.
Save Cheesebaron/ad84740c9bffa7e255c8 to your computer and use it in GitHub Desktop.
WebView Location prompt sample
using Android;
using Android.App;
using Android.Content;
using Android.Webkit;
using Android.OS;
[assembly: UsesPermission(Name = Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Name = Manifest.Permission.Internet)]
namespace WebViewLocation
{
[Activity(Label = "WebView Location", MainLauncher = true, Icon = "@drawable/icon")]
public class WebViewLocationActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var webview = new WebView(this);
webview.Settings.JavaScriptEnabled = true;
webview.Settings.SetGeolocationEnabled(true);
webview.SetWebViewClient(new MyWebViewClient());
webview.SetWebChromeClient(new MyWebChromeClient(this));
webview.LoadUrl("https://maps.google.com");
SetContentView(webview);
}
}
public class MyWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
}
public class MyWebChromeClient : WebChromeClient
{
private readonly Context _context;
public MyWebChromeClient(Context context)
{
_context = context;
}
public override void OnGeolocationPermissionsShowPrompt(string origin, GeolocationPermissions.ICallback callback)
{
const bool remember = false;
var builder = new AlertDialog.Builder(_context);
builder.SetTitle("Location")
.SetMessage(string.Format("{0} would like to use your current location", origin))
.SetPositiveButton("Allow", (sender, args) => callback.Invoke(origin, true, remember))
.SetNegativeButton("Disallow", (sender, args) => callback.Invoke(origin, false, remember));
var alert = builder.Create();
alert.Show();
}
}
}
@Cheesebaron
Copy link
Author

@josedavidpc310 too bad. This is a 4 year old sample. Things have changed since then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment