Java 打开GPS功能webview

Java 打开GPS功能webview,java,android,webview,geolocation,gps,Java,Android,Webview,Geolocation,Gps,我的网站有一个需要访问用户位置的webView,它通过按下按钮并在表单中显示位置来访问用户位置。我需要从webView中找到一种方法,要求用户在单击按钮时打开gps(它有id=“locate button”)。我如何在Android studio中做到这一点 我的代码: MainActivity.java public class MainActivity extends AppCompatActivity { private WebView webview; @Override prote

我的网站有一个需要访问用户位置的webView,它通过按下按钮并在表单中显示位置来访问用户位置。我需要从webView中找到一种方法,要求用户在单击按钮时打开gps(它有
id=“locate button”
)。我如何在Android studio中做到这一点

我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {

private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    webview = (WebView) findViewById(R.id.webView);

    webview.setWebViewClient(new WebViewClient());
    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setDatabaseEnabled(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webview.getSettings().setGeolocationEnabled(true);
    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }
    });
    webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            // hide element by class name
            webview.loadUrl("javascript:(function() { " + "document.getElementsByClassName('menu-icone-container')[0].style.display='none';  })()");
        }
    });
    webview.loadUrl("http://www.example.it");
}
编辑: 我找到了一种方法来检查gps是否已关闭,并提示用户进行gps设置,但我只能在应用程序启动时调用此方法,而不能在按下按钮时调用

 public void CheckEnableGPS() {
    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (!provider.contains("gps")){
        showSettingAlert();
    }

}

public void showSettingAlert()
{
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    alertDialog.setTitle("Impostazioni GPS");
    alertDialog.setMessage("Per ottenere la posizione corrente il GPS deve essere attivo, attivarlo?");
    alertDialog.setPositiveButton("Impostazioni", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });
    alertDialog.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    alertDialog.show();
}

当您的活动启动时,您可以要求用户打开其GPS。 第一步是创建位置请求

      LocationRequest mLocationRequest = new LocationRequest();
      locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
      locationRequest.setInterval(1000);
      locationRequest.setFastestInterval(5000);
然后,您必须创建位置请求设置:

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
 .addLocationRequest(mLocationRequest);
接下来检查是否满足当前位置设置:

SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
SettingsClient=LocationServices.getSettingsClient(此);
Task Task=client.checkLocationSettings(builder.build());
接下来,提示用户更改位置设置

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
    // All location settings are satisfied. The client can initialize
    // location requests here.
    // ...
    }
});
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    if (e instanceof ResolvableApiException) {
        // Location settings are not satisfied, but this can be fixed
        // by showing the user a dialog.
        try {
            // Show the dialog by calling startResolutionForResult(),
            // and check the result in onActivityResult().
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(MainActivity.this,
                    REQUEST_CHECK_SETTINGS);
        } catch (IntentSender.SendIntentException sendEx) {
            // Ignore the error.
        }
    }
}
});
task.addOnSuccessListener(这个,新的OnSuccessListener(){
@凌驾
成功时公共无效(位置设置响应位置设置响应){
//满足所有位置设置。客户端可以初始化
//这里有位置请求。
// ...
}
});
task.addOnFailureListener(这是新的OnFailureListener(){
@凌驾
public void onFailure(@NonNull异常e){
if(可解析APIexception的实例){
//不满足位置设置,但可以修复此问题
//通过向用户显示一个对话框。
试一试{
//通过调用startResolutionForResult()显示对话框,
//并在onActivityResult()中检查结果。
ResolvableApiException resolvable=(ResolvableApiException)e;
可解析。开始解决结果(main activity.this,
请求检查设置);
}catch(IntentSender.SendIntentException sendEx){
//忽略错误。
}
}
}
});

请查看Officel文档:

使用此代码提示用户启用位置设置,用户无需打开手机的设置窗口:

private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();
    final String TAG = "YOUR-TAG-NAME";
    final int REQUEST_CHECK_SETTINGS = 0x1;

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i(TAG, "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i(TAG, "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}
private void displayLocationSettingsRequest(上下文){
GoogleAppClient GoogleAppClient=新的GoogleAppClient.Builder(上下文)
.addApi(LocationServices.API).build();
googleApiClient.connect();
最后一个字符串TAG=“YOUR-TAG-NAME”;
最终整数请求检查设置=0x1;
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
locationRequest.setInterval(10000);
locationRequest.SetFastTestInterval(10000/2);
LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult=LocationServices.SettingsApi.checkLocationSettings(GoogleAppClient,builder.build());
result.setResultCallback(新的ResultCallback(){
@凌驾
公共void onResult(位置设置结果){
最终状态状态=result.getStatus();
开关(status.getStatusCode()){
案例位置设置StatusCodes.SUCCESS:
Log.i(标记“满足所有位置设置”);
打破
案例位置设置StatusCodes.RESOLUTION_要求:
Log.i(标记“不满足位置设置。向用户显示一个对话框以升级位置设置”);
试一试{
//通过调用startResolutionForResult()显示对话框,并检查结果
//在onActivityResult()中。
status.startResolutionForResult(MainActivity.this,请求检查设置);
}catch(IntentSender.sendtintentexe){
Log.i(标记“PendingEvent无法执行请求”);
}
打破
案例位置设置StatusCodes.SETTINGS\u CHANGE\u不可用:
Log.i(标记“位置设置不足,无法在此修复。未创建对话框”);
打破
}
}
});
}

最佳解决方案,完美地为我工作

单击附近的按钮或任何地理位置许可按钮、链接时,WebView将请求GPS许可

1.首先,我们必须使用WebChromeClient调用GeolocationPermissions.Callback

webView.setWebChromeClient(new WebChromeClient() {

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

                final boolean remember = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyAlertDialogStyle);
                      builder.setTitle("Locations");
                      builder.setIcon(R.mipmap.ic_launcher);
                      builder.setMessage("Would like to use your Current Location ")
                             .setCancelable(true).setPositiveButton("Allow", (dialog, id) -> {
                                  // origin, allow, remember
                                 callback.invoke(origin, true, remember);

                                 displayLocationSettingsRequest();

                                 int result = ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
                                 if (result == PackageManager.PERMISSION_GRANTED) {

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

                          }).setNegativeButton("Don't Allow", (dialog, id) -> {
                          // origin, allow, remember
                                callback.invoke(origin, false, remember);
                          });
                         AlertDialog alert = builder.create();
                           alert.show();
            }
}
  • 当用户单击允许GPS权限时,WebView将调用GPS设置功能,在我的例子中是
    displayLocationSettingsRequest()
  • 3.在中为LocationSettingsRequest添加GoogleAppClient

    private void displayLocationSettingsRequest() {
            GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API).build();
            googleApiClient.connect();
            final String TAG = "YOUR-TAG-NAME";
            final int REQUEST_CHECK_SETTINGS = 0x1;
    
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(10000);
            locationRequest.setFastestInterval(10000 / 2);
    
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
            builder.setAlwaysShow(true);
    
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(result1 -> {
                final Status status = result1.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.i(TAG, "All location settings are satisfied.");
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
    
                        try {
                            // Show the dialog by calling startResolutionForResult(), and check the result
                            // in onActivityResult().
                            status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            Log.i(TAG, "PendingIntent unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                        break;
                }
            });
        }
    
    将此添加到活动中

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            return;
            }
                // other 'case' lines to check for other
                // permissions this app might request
        }
    }
    

    看看
    android.webkit.JavascriptInterface
    注释。我不记得如何准确地使用它,所以我没有把它作为一个答案。@dedda1994我读过关于它的文章,它可能是答案,但我无法让它工作。非常感谢,但我仍然需要一种方法,当我的webview中的一个按钮被点击时使用它……非常感谢你,您节省了很多时间,访问该位置时,此特定的弹出窗口不会出现。
    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            return;
            }
                // other 'case' lines to check for other
                // permissions this app might request
        }
    }