I have a webview and I would like to run Android.getLocation () from javascript to give me the user's location using json, I've done this:
MainActivity.java
[...]
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
this.myWebView = (WebView) this.findViewById(R.id.webView);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.loadUrl("file:///android_asset/example.html");
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
}
[...]
WebAppInterface.java
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.webkit.JavascriptInterface;
import org.json.JSONException;
import org.json.JSONObject;
public class WebAppInterface extends Activity {
Context context;
public WebAppInterface(Context context) {
this.context = context;
}
[...]
private LocationManager locManager;
@JavascriptInterface
public JSONObject getLocation() throws JSONException {
locManager = (LocationManager) getSystemService(this.context.LOCATION_SERVICE); #Me da error en esta linea
Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
JSONObject location = new JSONObject();
location.put("latitude", loc.getLatitude());
location.put("longitude", loc.getLongitude());
return location;
}
[...]
And obviously I've put the permissions
but when executing from javascript I get an error in the first line of getLocation () and I do not know why, apparently it seems to be fine.
Thank you very much