android webview 地理定位

新手上路,请多包涵

我必须在 WebView 中检索用户的位置。我使用以下 Javascript 执行此操作:

 function getLocation() {
   navigator.geolocation.getCurrentPosition(displayLocation, handleError);
}

但是权限请求弹出窗口永远不会打开。

我已经设置了这些设置:

 ws.setJavaScriptEnabled(true);
ws.setGeolocationEnabled(true);
ws.setJavaScriptCanOpenWindowsAutomatically(true);

WebView 中访问用户位置的正确方法是什么?

原文由 Ste 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 466
1 个回答

当从 Webview 请求位置时,您需要动态请求权限

确保您已将 ACCESS_FINE_LOCATION 添加到清单

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

在顶级类中定义您的回调和来源,以便能够将它们分配给 ChromeClient 提供的回调和来源

public class MainActivity extends AppCompatActivity {

    private android.webkit.WebView myWebView;
    String mGeoLocationRequestOrigin = null;
    GeolocationPermissions.Callback  mGeoLocationCallback = null;

...................................................

处理 geoLocation 请求并将值分配给回调,以便在授予权限后能够使用它们

      myWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                                                           final GeolocationPermissions.Callback callback) {

                int permissionCheckFineLocation = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
                if (permissionCheckFineLocation!= PackageManager.PERMISSION_GRANTED) {
                    mGeoLocationCallback=callback;
                    mGeoLocationRequestOrigin=origin;
                    //requesting permission
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
                }

                else {// permission and the user has therefore already granted it
                    callback.invoke(origin, true, false);
                }

            }
        });

一旦获得许可,使用 origin 调用回调

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            //you have the permission now.
            if(requestCode==123) {
                mGeoLocationCallback.invoke(mGeoLocationRequestOrigin, true, false);
            }
        }

原文由 Muhammad Mufeez Ahmed 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题