Html Web Page Location Operation in Android WebView

Using the location API provided by HTML5 can help web pages to get the current location information of user equipment. But if we open a web page in a...

Using the location API provided by HTML5 can help web pages to get the current location information of user equipment. But if we open a web page in an Android application, the WebView we use in the Hybrid development model, including the application itself, needs to be set up to support the location function of Embedded Web pages.

Here is a simple web page source code with a JavaScript code to request location from the host browser:

<!DOCTYPE html> <head> </head> <body> <button onclick="fetchLocation()">Get location</button> <script> var tipsEle = document.getElementById('tips') function fetchLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError) } else { alert('Current devices do not support positioning!') } } function onGeoSuccess(event){ alert("Success: " + event.coords.latitude + ", " + event.coords.longitude) } function onGeoError(event){ alert("Error code " + event.code + ". " + event.message) } </script> </body>

Simple Description: (For detailed use of HTML5 Location API, you can refer to the link: New Bird Tutorial - HTML5 Geolocation)

  • The navigator.geolocation attribute determines whether the current hardware browser environment supports localization.

  • getCurrentPosition() function, on the premise of supporting positioning, initiates request positioning, and passes two functions of success and failure of positioning as callback parameters.

Then add the following settings to our WebView: (assume that the test html file above is placed in the assets directory)

WebView contentWv = (WebView) findViewById(R.id.wv_content); WebSettings settings = contentWv.getSettings(); settings.setJavaScriptEnabled(true); contentWv.setWebChromeClient(new WebChromeClient(){ @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, true); super.onGeolocationPermissionsShowPrompt(origin, callback); } }); contentWv.loadUrl("file:///android_asset/location.html");

The code is simple, and the most important thing is to rewrite this method of WebChromeClient:

onGeolocationPermissionsShowPrompt()

When a web page initiates a location request, this method is called to the host WebView, and the developer handles the request on his own. As you can see, the example contains such a line of code:

callback.invoke(origin, true, true);

This line of code is used to process positioning requests, and usually gives users a pop-up window to request positioning permissions. The parameter of the second boolean type denotes whether to grant Web page location permission, while the parameter of the third boolean type denotes whether to retain this permission status.

It is noteworthy that the third parameter setting affects the WebView in the entire application. If we have processed a Web page location request in a WebView of a page and set the third parameter to true, that is, in the case of reserved status, when the next page is opened on another page or this page, the user will no longer be asked for location permission, but will directly perform the location operation.

In general, it is more appropriate to set up a dialog box in the callback function to inform the user whether to authorize the location operation. Better yet, it can also help users detect whether the device's system positioning is open or not. If not, prompt the user and jump to the settings interface.

Sample code to detect whether system positioning is open:

private boolean isSystemLocationEnable() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); boolean gpsLocationEnable = manager.isProviderEnabled(LocationManager.GPS_PROVIDER); boolean networkLocationEnable = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); return gpsLocationEnable && networkLocationEnable; }

Jump to the location interface in the system settings:

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent);

Finally, don't forget to add location-related permissions to the Manifest manifest file, including network permissions, of course: (through GPS precise positioning and WI-FI rough positioning)

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/>

The effect of this sample page code call is as follows:

On the whole, the way to use it is quite simple. Is that the way to use it absolutely foolproof?

As mentioned earlier, the premise of using HTML5 location API to get user location is that the browser or native WebView environment in our Android system supports location operations. In fact, this method is not completely stable after testing. Especially in the complex environment of various ROM s of domestic manufacturers, there are quite a number of brands of mobile phones that do not support this positioning operation. Even if you use the same mobile phone, you will encounter different browser apps for positioning support.

Therefore, HTML5's own positioning operation can only be used as an auxiliary means. It is safer for developers to locate SDK in native code through third parties such as Baidu and Gaode to get user location information. When opening webpage in WebView, they pass it to webpage by splicing URL parameters. Web pages decide by themselves, if the URL does not contain location information, then through their own API to initiate location requests.

Or operate indirectly by interacting JS code of HTML pages with native Java code. For knowledge about JS and Java interaction, you can refer to my article:

Android WebView: Summary of Java and JavaScript Interaction

About me: Yifeng, blog address: http://yifeng.studio/ Sina Weibo: IT Yi Feng

Wechat scans two-dimensional codes. Welcome to pay attention to my personal public number: Android Notebook

Not only share my original technical articles, but also the programmer's career reverie.

26 May 2019, 16:25 | Views: 3293

Add new comment

For adding a comment, please log in
or create account

0 comments