我尝试使用自定义WebChromeClient
在webView中打开Google地图并获取我的位置,但地图显示无法设置位置。
完整代码:
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
}, 0);
return;
}
WebView webView = (WebView)findViewById(R.id.wv) ;
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabasePath("");
webView.getSettings().setGeolocationDatabasePath( this.getFilesDir().getPath() );
webView.setWebChromeClient(new webChromeClient());
webView.getSettings().setGeolocationEnabled(true);
webView.setWebViewClient(new webViewClient());
webView.getSettings().setGeolocationDatabasePath(
webView.getContext().getFilesDir().getPath());
webView.loadUrl("https://google.ru/maps");
}
class webViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
class webChromeClient extends WebChromeClient{
@Override
public void onGeolocationPermissionsHidePrompt() {
super.onGeolocationPermissionsHidePrompt();
Log.d("MainActivity","onGeolocationPermissionHidePromt");
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, true);
Log.d("MainActivity","onGeolocationPermissionShowPromt");
}
}
}
在onGeolocationPermissionsShowPrompt
中Log.d
是静默的,意味着无法调用。但为什么呢?
清单:
<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" />
仅在布局中webView
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wv"/>
有什么问题?提前致谢。 附:抱歉我的英文。