Hola, tengo un webview y me gustaría que al ejecutar Android.getLocation() desde javascript me diera la localización del usuario mediante json , he hecho esto:
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;
}
[...]
Y obviamente he puesto los permisos
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
pero al ejecutar desde javascript me da error en la primera linea de getLocation() y no se el porque, aparentemente parece estar bien