Android: 如何開啟webview的LBS功能 ,不做過多解釋代碼全貼在下面。
首先想要用到手機的LBS功能,必須在androidManifest.xml中請求權限.
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
webview加載URL以及相關設置
- private void loadUrl(){
- browser.getSettings().setJavaScriptEnabled(true);
- browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
- browser.getSettings().setGeolocationEnabled(true);
- GeoClient geo = new GeoClient();
- browser.setWebViewClient(new PTCWebViewClient(this, browser));
- browser.setWebChromeClient(geo);
- String origin = "";
- geo.onGeolocationPermissionsShowPrompt(origin, this);
- browser.loadUrl("http://www.mytransport.sg");
- }
PTCWebViewClient.java
- public class PTCWebViewClient extends WebViewClient {
-
- private ProgressDialog pd;
-
- public PTCWebViewClient(Context con, final WebView web){
- pd = new ProgressDialog(con);
- pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- pd.setTitle("MTC LTA");
- pd.setMessage("Loading, please wait...");
- pd.setIcon(R.drawable.icon);
- pd.setButton("Cancel", new ProgressDialog.OnClickListener(){
- @Override
- public void onClick(DialogInterface dialog, int which) {
- web.stopLoading();
- }
- });
- pd.setIndeterminate(false);
- pd.setCancelable(true);
- }
-
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- @Override
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- super.onPageStarted(view, url, favicon);
- pd.show();
- }
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- pd.dismiss();
- }
- }
GeoClient.java
- class GeoClient extends WebChromeClient {
-
- @Override
- public void onGeolocationPermissionsShowPrompt(String origin,
- Callback callback) {
- super.onGeolocationPermissionsShowPrompt(origin, callback);
- callback.invoke(origin, true, false);
- }
- }