如何使用webview.loadURL从javascript(Android)获取变量

时间:2013-04-21 21:30:42

标签: javascript android webview geolocation android-jsinterface

我打算尽可能清楚地说明这一点。我通常不是最好问清楚的问题,所以感谢您提前阅读本文并发布任何建议。

我正在编写一个简单的Android应用程序,需要用户定位。我正在使用webview与HTML navigator.geolocation.getCurrentPosition一起跟踪用户。

我遇到的问题是将HTML文件中收集的坐标放到我的android / java应用程序中。我在webview中使用javascriptInterface在两者之间进行通信。

这是我的java代码中的webview声明。

//Create the web-view
final WebView 
wv = (WebView) findViewById(R.id.webview);  
wv.getSettings().setJavaScriptEnabled(true);
//Creates the interface "Android". This class can now be referenced in the HTML file.
wv.addJavascriptInterface(new WebAppInterface(this),"Android");
wv.setWebChromeClient(new WebChromeClient());

这是WebAppInterface代码

public class WebAppInterface extends Activity 
 {
  Context mContext;

  /** Instantiate the interface and set the context */
  WebAppInterface(Context c) {mContext = c;}

  //Used to display Java Toast messages for testing and debugging purposes 
  @JavascriptInterface
  public void showToast(String toast) {
      Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
 }

  @JavascriptInterface
  public void storeCoord(String myLat,String myLong) 
  {
    Log.d("Coordinate Log","HTML call to storeCoords()");

    //Log.d("Coord Lat", myLat);
    //Log.d("Coord Long", myLong);

  }
}

最后但并非最不重要的是,这是我的HTML代码

<!DOCTYPE html>
<html>
  <body>        
    <script type="text/javascript">

        function storePosition(position) 
        {
            Android.showToast("In storePosition()");                                        

            myLat = position.coords.latitude;
            myLong = position.coords.longitude;

            Android.showToast(myLat +" "+ myLong);  
                            Android.storeCoord(myLat,myLong);               
        }

        function fail(error){}  

        if (navigator.geolocation) 
        {
            navigator.geolocation.getCurrentPosition(storePosition,fail,{enableHighAccuracy:true,timeout:10000});
        }   
    </script>
</body>

截至目前,每次我想收集用户的坐标时我都使用以下代码行

wv.loadUrl("file:///android_asset/CurrentLocationCoordinates.html");

一直工作正常,直到调用storePosition函数。我认为这与我没有专门从loadURL调用storePosition函数这一事实有关,所以我试过

wv.loadUrl("javascript:storePosition()");

哪个有效。但是!! ...我没有从navigator.geolocation.getCurrentPosition收集的位置发送到函数storedPosition,所以显然没有任何反应。我已经在网络上的任何地方搜索了一个解决方案,我得出结论,我根本不明白webview.LoadURL函数是如何工作的。我需要将坐标存储在我的Android应用程序中!

再次感谢您的时间和建议。

0 个答案:

没有答案