【问题标题】:getting location in WebView via js通过 js 在 WebView 中获取位置
【发布时间】:2020-12-26 04:24:37
【问题描述】:

我正在尝试创建 WebView,它将通过 js 获得 GPS 本地化,但是当我单击应该显示本地化的按钮时: 在 android 4.1.1(模拟器)中:“错误代码 2。无法启动地理定位服务 在 android 4.1.2(phone) 中什么也没发生 在 android 6.0(emulator) 中也一样,只是没有任何反应

我的权限:

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

我的设置:

webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);

        webView.getSettings().setSaveFormData(false);
        webView.getSettings().setSavePassword(false);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());

WebChrome客户端:

WebChromeClient webChromeClient = new WebChromeClient(){

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                // callback.invoke(String origin, boolean allow, boolean remember);
                callback.invoke(origin, true, false);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE);

            }

            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE);
                return false;
            }

        };

WebViewClient:

WebViewClient webViewClient = new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url){
                progressBar.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                refreshBtn.setVisibility(View.VISIBLE);
            }
        };

最后,我有这行代码:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);

和js代码(不是我的代码):

    <script>
function getLocationConstant()
{
  if(navigator.geolocation)
  {
   navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
  } else {
   alert("Brak obsługi GPS");
  }
}


function onGeoSuccess(event)
{
  document.getElementById("skad").value =  event.coords.latitude+", "+event.coords.longitude;
 document.getElementById('szk').click();

}


function onGeoError(event)
{
  alert("Error code " + event.code + ". " + event.message);
}


</script>

<input type="text" name="skad" style="width:278px;" id="skad" >

【问题讨论】:

  • 会有一些堆栈跟踪。在此处添加。
  • 我只从 4.1.1 获得它:W/EGL_emulation: eglSurfaceAttrib 未实现,android 6.0 和 4.1.2 手机打印什么
  • 我遇到了同样的问题,尤其是当用户在他们的设置中禁用定位时,你找到原因了吗?
  • 我已经解决了,但现在我不记得是什么问题了。不幸的是,我只能在晚上检查它。
  • @Jeremy:我在设置中关闭位置时遇到问题。没有打印错误日志。无法在没有日志的情况下应用任何修复。在 chrome 浏览器的同一页面中.. 在设置中关闭位置时.. 它会向用户显示提示。

标签: android webview gps


【解决方案1】:

我不知道为什么,但现在可以了。有使用 gps 位置的带有 webView 的简单应用程序的代码。
主要活动:

package com.qiteq.gpswebview;

import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WebView wv = new WebView(this);
        wv.loadUrl("http://qiteq.pl/stack/index.html");
        setContentView(wv);

        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        }, 0);

        wv.getSettings().setJavaScriptEnabled(true);


        wv.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });


    }
}

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qiteq.gpswebview">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

还有index.html:

<script>
function getLocationConstant()
{
  if(navigator.geolocation)
  {
   navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
  } else {
   alert("No GPS support");
  }
}


function onGeoSuccess(event)
{
    document.getElementById("location").value =  event.coords.latitude+", "+event.coords.longitude;
    alert("Success: "+event.coords.latitude+", "+event.coords.longitude);
}


function onGeoError(event)
{
  alert("Error code " + event.code + ". " + event.message);
}


</script>

<input type="text" name="location" id="location" style="width:278px;">
<button onclick="getLocationConstant()" >Click</button>

【讨论】:

  • YESSSSSS。对我来说关键是 ActivityCompat.requestPermissions(...) 块
【解决方案2】:

检查这个代码功能太好了,sdk>4实现下一个,加入请求权限。

@Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            //Log.i(TAG, "onGeolocationPermissionsShowPrompt()");

            final boolean remember = true;
            AlertDialog.Builder builder = new AlertDialog.Builder(vistamaps.this);
            builder.setTitle("Locations");
            builder.setMessage("Would like to use your Current Location ")
                    .setCancelable(true).setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // origin, allow, remember
                    callback.invoke(origin, true, remember);
                    int result = ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
                    if (result == PackageManager.PERMISSION_GRANTED) {

                    } else {
                        ActivityCompat.requestPermissions(vistamaps.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 101);
                    }
                }
            }).setNegativeButton("Don't Allow", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // origin, allow, remember
                    callback.invoke(origin, false, remember);
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }

【讨论】:

  • 和下一个代码,看看会发生什么,实现到类 webChromeClient -- @Override public void onPermissionRequest(PermissionRequest request) { Log.e("WebView", "onPermissionRequest: "+request.toString ()); super.onPermissionRequest(request); }
猜你喜欢
  • 2011-01-31
  • 1970-01-01
  • 2013-09-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2019-01-28
  • 2018-01-30
相关资源
最近更新 更多