Skip to content Skip to sidebar Skip to footer

Enable Geolocation On Webview

Good Evening. I'm on making Tracking Application on Android using Webview. i got problem because the system all works well beside the location. in manifest i got this permission se

Solution 1:

First, the Android manifest:

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.webview"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="5" /><uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><applicationandroid:icon="@mipmap/ic_launcher"android:label="@string/app_name" ><activityandroid:name=".GeoWebViewActivity"android:label="@string/app_name"android:theme="@android:style/Theme.NoTitleBar" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?><WebViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/webView1"android:layout_width="fill_parent"android:layout_height="fill_parent" />

And finally, here is the complete app, consisting only of GeoWebViewActivity:

package com.example.webview;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * A minimal WebView app with HTML5 geolocation capability
 *
 * @author David M. Chandler
 */publicclassGeoWebViewActivityextendsActivity {

    /**
     * WebViewClient subclass loads all hyperlinks in the existing WebView
     */publicclassGeoWebViewClientextendsWebViewClient {
        @OverridepublicbooleanshouldOverrideUrlLoading(WebView view, String url) {
            // When user clicks a hyperlink, load in the existing WebView
            view.loadUrl(url);
            returntrue;
        }
    }

    /**
     * WebChromeClient subclass handles UI-related calls
     * Note: think chrome as in decoration, not the Chrome browser
     */publicclassGeoWebChromeClientextendsWebChromeClient {
       @OverridepublicvoidonGeolocationPermissionsShowPrompt(String origin,
                                               GeolocationPermissions.Callback callback) {
        // Geolocation permissions coming from this app's Manifest will only be valid for devices with// API_VERSION < 23. On API 23 and above, we must check for permissions, and possibly// ask for them.Stringperm= Manifest.permission.ACCESS_FINE_LOCATION;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
            ContextCompat.checkSelfPermission(MainActivity.this, perm) == PackageManager.PERMISSION_GRANTED) {
            // we're on SDK < 23 OR user has already granted permission
            callback.invoke(origin, true, false);
        } else {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, perm)) {
                // ask the user for permission
                ActivityCompat.requestPermissions(MainActivity.this, newString[] {perm}, REQUEST_FINE_LOCATION);

                // we will use these when user responds
                mGeolocationOrigin = origin;
                mGeolocationCallback = callback;
            }
        }
    }


    @OverridepublicvoidonRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNullint[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_FINE_LOCATION:
                booleanallow=false;
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // user has allowed this permission
                    allow = true;
                }
                if (mGeolocationCallback != null) {
                    // call back to web chrome client
                    mGeolocationCallback.invoke(mGeolocationOrigin, allow, false);
                }
                break;
        }
    }

    WebView mWebView;

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webView1);
        // Brower niceties -- pinch / zoom, follow links in place
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.setWebViewClient(newGeoWebViewClient());
        // Below required for geolocation
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.setWebChromeClient(newGeoWebChromeClient());
        // Load google.com
        mWebView.loadUrl("http://www.google.com");
    }

    @OverridepublicvoidonBackPressed() {
        // Pop the browser back stack or exit the activityif (mWebView.canGoBack()) {
            mWebView.goBack();
        }
        else {
            super.onBackPressed();
        }
    }
}

Hope this helps.

Solution 2:

private boolean isLocationPermissionGrandted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
        } elseif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        } else {
            returntrue;
        }
    }


    private void getLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION}, PERMISSION_LOCATTION_CODE);
        } else {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_LOCATTION_CODE);
        }
    }
if (isLocationPermissionGrandted())
     initializeWebView();
else
     getLocationPermission();

Post a Comment for "Enable Geolocation On Webview"