Определение местоположения в WebView Android Studio
В моем сайте есть определение местоположения. Оно отлично работает но только в браузере. Я пытался сделать так чтоб и в WebView работало, однако ничего не вышло.
Код
WebView webView;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowContentAccess(true);
settings.setAppCacheEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setGeolocationDatabasePath(this.getFilesDir().getPath());
final Activity activity = this;
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
@Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('ukl_component-header')[0].style.display='none'; " +
"})()");
setContentView(webView);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
});
webView.setWebChromeClient(new android.webkit.WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(final String origin, final android.webkit.GeolocationPermissions.Callback callback) {
Log.i("TAG", "onGeolocationPermissionsShowPrompt()");
final boolean remember = false;
AlertDialog.Builder builder = new AlertDialog.Builder(UklonActivity.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);
}
}).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();
}
});
webView.loadUrl("https://m.uklon.com.ua/order");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Буду благодарен если скинете пример кода
Ответы (1 шт):
Хоть никто и не помог я смог решить проблему и пишу этот ответ для тех кто столкнется с тем же. Проблема заключалась в том что приложением с API 23+ недостаточно задать разрешение в файле манифеста его надо запрашивать у пользователя.
В файле манифеста все равно надо прописать разрешение на использование местоположения
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
И теперь чтобы запросить у пользователя разрешение надо прописать следующее
private final int REQUEST_CODE_PERMISSION_ACCESS_FINE_LOCATION = 100;
ActivityCompat.requestPermissions(UklonActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_PERMISSION_ACCESS_FINE_LOCATION);
Если пользователь даст разрешение повторный вызов диалогового окна с запросом на разрешение не произойдет. Однако если пользователь отключит службу сам либо не даст разрешение оно будет повторно появляться.