Question

This URL shows the snapshot of an emulator where I am showing my map in a web view. In that map When I click on Canvas link I want to call an Android activity from this HTML page given below.

Here is the HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
    xmlns="http://www.w3.org/1999/xhtml"> <head> <meta
    http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>How to parse XML and load data into HTML page</title>

<link rel="stylesheet"
    href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css" /> <script
    src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>

    <div id="map" class="dark" style="height:250px;"></div> 
    <div id="latitude"></div> <div id="longitude"></div> 
    <script type="text/javascript"> 
        function loadXMLDoc(XMLname) {    
            var xmlDoc;
          if (window.XMLHttpRequest) { 
                xmlDoc=new  window.XMLHttpRequest();
                xmlDoc.open("GET",XMLname,false);    
                xmlDoc.send("");
                return xmlDoc.responseXML;
            }   // IE 5 and IE 6
          else if (ActiveXObject("Microsoft.XMLDOM")) {
                xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async=false; 
                xmlDoc.load(XMLname);
              return xmlDoc;    
            }   

            alert("Error loading  document!");  
            return null; 
        }    
    </script>
    <body>    
        <script type="text/javascript">    
             xmlDoc=loadXMLDoc("AddressDetails.xml");   
             var M = xmlDoc.getElementsByTagName("task"); 
             var i; 
             for (i=0;i<M.length;i++){
                 var a = xmlDoc.getElementsByTagName("latitude")[i].childNodes[0].nodeValue;
                 var b = xmlDoc.getElementsByTagName("logitude")[i].childNodes[0].nodeValue;  
                 var map = L.map('map').setView([a,b],13); break; 
             }

             for (i=0;i<M.length;i++) {
                 document.write("<div style='width:450px;'>")
                 document.write("<h2>"+xmlDoc.getElementsByTagName("id")[i].childNodes[0].nodeValue+"</h2>");
                 document.write("<p>"+xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue+"</p>");
                 document.write("<p>"+xmlDoc.getElementsByTagName("address")[i].childNodes[0].nodeValue+"</p>");
                 document.write("<p>"+xmlDoc.getElementsByTagName("mobile")[i].childNodes[0].nodeValue+"</p>");
                 document.write("<p>"+xmlDoc.getElementsByTagName("assignwork")[i].childNodes[0].nodeValue+"</p>");
                 document.write("<p>Latitude<span>:</span>"+xmlDoc.getElementsByTagName("latitude")[i].childNodes[0].nodeValue+"</p>");
                 document.write("<p>Longitude<span>:</span>"+xmlDoc.getElementsByTagName("logitude")[i].childNodes[0].nodeValue+"</p>");
                 document.write("</div>")

                 var userName = xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue;   
                 var a = xmlDoc.getElementsByTagName("latitude")[i].childNodes[0].nodeValue; 
                 var b = xmlDoc.getElementsByTagName("logitude")[i].childNodes[0].nodeValue;
                 var assignwork = xmlDoc.getElementsByTagName("assignwork")[i].childNodes[0].nodeValue;
                 var userid = i;
                 alert(userName);

                 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
                 {
                     attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                 }).addTo(map);

                 // add a marker in the given location, attach some  popup content to it and open the popup   
                L.marker([a,b]).addTo(map)
                    .bindPopup('<a href="http://www.google.com"></b>Get Direction</b></a><br/><a 
                href="http://www.google.com">Status</a><br/><a id="issueID'+userid+'" 
                href="#" onClick="setHtml(this.id)">Canvas</a>').openPopup();
                var circle = L.circle([a,b], 500, {
                    color: 'red',
                    fillColor: '#f03',
                   fillOpacity: 0.5 
                }).addTo(map);
            }
            map.addLayer(marker);

            function setHtml(str) { 
                alert(str);   
                var HTML = str;  
                window.HTMLOUT.showHTML(HTML); 
            }  
        </script>
    </body> 
</html>

Activity class

   package com.locationTracker.periscope;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.TextView;



public class MapActivity  extends Activity {
  @SuppressLint("SetJavaScriptEnabled")
  private WebView myWebView;
  private TextView mapTextView;
  private String url ="file:///android_asset/Map.html";

  @SuppressLint("SetJavaScriptEnabled")
  @SuppressWarnings("deprecation")
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = new String("file:///android_asset/Map.html");
        setContentView(R.layout.leaflet_map);
        this.setTitle("Location Map");
        // Obtain the webView by ID

        if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
          .permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }
        MyJavaScriptInterface js =new MyJavaScriptInterface();
        initComponent();
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        // performance hacks!
        webSettings.setRenderPriority(RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        // multi-touch zoom
        webSettings.setBuiltInZoomControls(true);
       /* webSettings.setDisplayZoomControls(false);*/
        myWebView.getSettings().setLoadsImagesAutomatically(true);
        myWebView.setWebChromeClient(new WebChromeClient());
        myWebView.addJavascriptInterface(js, "Android");
        myWebView.setWebViewClient(new WebViewClient());
        //myWebView.loadUrl("http://widgets.ign.com/global/wikis/wikimap.html?full=true&?popup=iphone");
        myWebView.loadUrl("file:///android_asset/Map.html");
        myWebView.setWebViewClient(new WebViewClient());


    }

  public void initComponent(){

    generateId();
  }

  public void generateId(){

    myWebView = (WebView) findViewById(R.id.webView);
    mapTextView = (TextView) findViewById(R.id.leafletTV);
  }


  class MyJavaScriptInterface
  {
      @SuppressWarnings("unused")
      public void showHTML(final String html)
      {
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  //MapActivity.this.mapTextView.setText(html);
                MapActivity.this.startActivity(new Intent(MapActivity.this, CreateIssue.class));
              }
          });
      }
  }
}
Was it helpful?

Solution

you need to pass a class instance to bind to JavaScript

private final class JsInterface {
          public void launchIntent(final String payload) {
             Activity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                   // use the payload if you want, attach as an extra, switch destination, etc.
                   Activity.this.startActivity(new Intent(Activity.this, SomeOtherActivity.class));
                }
             });
          }
       }

add that to the WebView with

final JavaScriptInterface js = new JavaScriptInterface(this);

webView.addJavascriptInterface(js, "Android");

Check this link for more details

OTHER TIPS

Check this stackoverflow

Android SDK WebView call Activity

Basically you can use the javascript interface for a webview for launching activity intent

To start an Activity from (possibly) any browser you can add an Intent filter like this in AndroidManifest.xml:

<intent-filter>
   <action android:name="android.intent.action.VIEW" /> 
   <category android:name="android.intent.category.DEFAULT" /> 
   <category android:name="android.intent.category.BROWSABLE" /> 
   <data android:scheme="com.example.myscheme" />
</intent-filter>

and then add a link like this to the desired page:

<a href="com.example.myscheme://path/here">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top