【发布时间】:2019-01-29 16:58:14
【问题描述】:
我的网站有一个 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();
}
【问题讨论】:
-
看看
android.webkit.JavascriptInterface注解。我不记得具体如何使用它,所以我不把它作为答案。 -
@dedda1994 我已经读过它,它可能是答案,但我无法让它工作
标签: java android webview geolocation gps