Android The WebKit Browser Victor Matos Cleveland State University Notes are based on: Android Developers Google.

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 4 Overview Overview of Sensors Programming Tutorial 1: Tracking location with GPS and Google.
Advertisements

Android The WebKit Browser Notes are based on: Android Developers Google Maps Javascript API V3 Basics
Android architecture overview
Smartphone Apps Development Team Weiqing Li Lijun Zhu Man Li.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
The Android Development Environment.  Getting started on the Android Platform  Installing required libraries  Programming Android using the Eclipse.
User Interface Android Applications. Activities An activity presents a visual user interface. Each activity is given a default window to draw in. The.
Android 101 Application Fundamentals January 29, 2010.
Cosc 4755 Blackberry and Android Embedding the browser in your app.
Basic, Basic, Basic Android. What are Packages? Page 346 in text Package statement goes before any import statements Indicates that the class declared.
11 Using the Google Maps API. 2 Objectives You will be able to Use the Google Maps API to display a map of any location on an HTML page. Programatically.
Android Application Development with Java UPenn CS4HS 2011 Chris Murphy
@2011 Mihail L. Sichitiu1 Android Introduction Hello World.
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
Android Programming. Outline Preparation Create new project Build and Run a project Debug a project Deploy on devices.
Data Storage: Part 1 (Preferences)
Presented by…. Group 2 1. Programming language 2Introduction.
Mobile Programming Lecture 1 Getting Started. Today's Agenda About the Eclipse IDE Hello, World! Project Android Project Structure Intro to Activities,
Introduction to Android Programming Content Basic environmental structure Building a simple app Debugging.
Introducing the Sudoku Example
CS378 - Mobile Computing Web - WebView and Web Services.
Windows Internet Explorer 9 Chapter 1 Introduction to Internet Explorer.
Google Maps API. Static Maps send an HTTP GET request receive an image (PNG, GIF, JPEG) no javascript needed encode params in URL example:
Introduction to Android. Android as a system, is a java based operating system that runs on the Linux kernel. The system is very lightweight and full.
Mobile Programming Lecture 6
DUE Hello World on the Android Platform.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
Android Accessing GPS Ken Nguyen Clayton State University 2012.
CS378 - Mobile Computing Web - WebView and Web Services.
Networking: Part 1 (Web Content). Networking with Android Android provides A full-featured web browser based on Chromium, the open source browser engine.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
Maps Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
Webview and Web services. Web Apps You can make your web content available to users in two ways in a traditional web browser in an Android application,
Announcements Homework #2 will be posted after class due Thursday Feb 7, 1:30pm you may work with one other person No office hours tonight (sorry!) I will.
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
FriendFinder Location-aware social networking on mobile phones.
TCS Internal Maps. 2 TCS Internal Objective Objective :  MAPS o Integration of Maps.
Microsoft Office 2008 for Mac – Illustrated Unit D: Getting Started with Safari.
Cosc 5/4730 Embedding the browser in your app. Embedding the browser For many applications, you may not nothing more then the web browser – But you want.
XP New Perspectives on Macromedia Dreamweaver MX 2004 Tutorial 5 1 Adding Shared Site Elements.
COMPARING CROSS-PLATFORM DEVELOPMENT APPROACHES FOR MOBILE APPLICATIONS Henning Heitkötter, Sebastian Hanschke and Tim A. Majchrzak Department of Information.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Chapter 5: Investigate! Lists, Arrays, and Web Browsers.
1. 2 Android location services Determining a device’s current location Tracking device movements Proximity alerts.
1 Bus Tracker A Google Maps Application. 22 Objectives You will be able to Add an icon to a map created with the Google Maps API. Use Ajax techniques.
CS499 – Mobile Application Development Fall 2013 Location & Maps.
Android Programming.
PhoneGap, Processing.
Tonga Institute of Higher Education IT 141: Information Systems
Chapter 10: Web Basics.
Android Programming - Features
Android Application Web 1.
Cleveland State University
Android Introduction Hello World
Android Application Development 1 6 May 2018
Android Studio, Android System Basics and Git
Android Introduction Hello World.
WebView and Web Services
CHAPTER 9 APIS. CHAPTER 9 APIS WHAT IS AN API?
Designing Apps Using The WebView Control
Activities and Intents
ITEC535 – Mobile Programming
Sensors, maps and fragments:
Getting Started with Dreamweaver
תכנות ב android אליהו חלסצ'י.
Tonga Institute of Higher Education IT 141: Information Systems
Tonga Institute of Higher Education IT 141: Information Systems
Android Notifications
Mobile Programming Dr. Mohsin Ali Memon.
Activities, Fragments, and Intents
Presentation transcript:

Android The WebKit Browser Victor Matos Cleveland State University Notes are based on: Android Developers Google Maps Javascript API V3 Basics The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:

2 10. Android – UI – The WebKit Browser WebKit Browser 2 In Android you can embed the built-in Web browser as a widget in your own activities, for displaying HTML material or perform Internet browsing. The Android browser is based on WebKit, the same engine that powers Apple's Safari Web browser. Android uses the WebView widget to host the browser’s pages Applications using the WebView component must request INTERNET permission.

3 10. Android – UI – The WebKit Browser WebKit Browser 3 Browsing Power The browser will access the Internet through whatever means are available to that specific device at the present time (WiFi, cellular network, Bluetooth-tethered phone, etc.). The WebKit rendering engine used to display web pages includes methods to 1.navigate forward and backward through a history, 2.zoom in and out, 3.perform text searches, 4.load data 5.stop loading and 6.more.

4 10. Android – UI – The WebKit Browser WebKit Browser 4 Warning In order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file: This must be a child of the element. (see next example)

5 10. Android – UI – The WebKit Browser WebKit Browser 5 Example: A simple browsing experience Let’s go e-shopping <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:layout_width="fill_parent" android:layout_height="fill_parent" />

package cis493.demoui; import android.os.Bundle; import android.app.Activity; import android.webkit.WebView; public class AndDemoUI extends Activity { WebView public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); browser.loadUrl(" browser.getSettings().setJavaScriptEnabled(true); } Android – UI – The WebKit Browser WebKit Browser 6 Example: A simple browsing experience Let’s go e-shopping This app is hard-wired to eBay

<manifest xmlns:android=" package="cis493.demoui" android:versionCode="1" android:versionName="1.0"> Android – UI – The WebKit Browser WebKit Browser 7 Example: A simple browsing experience Let’s go e-shopping - Manifest

8 10. Android – UI – The WebKit Browser WebKit Browser 8 Warning If you set the URL to a site whose pages depend on Javascript you may see an empty, white screen. By default Javascript is turned off in WebView widgets. If you want to enable Javascript, call : myWebView.setSettings().setJavaScriptEnabled(true); on the WebView instance. To be discussed later in this chapter.

9 10. Android – UI – The WebKit Browser WebKit Browser 9 Warning Under SDK 1.5 a WebView has a built-in Option Menu Using Go optionUsing More option

Android – UI – The WebKit Browser WebKit Browser 10 Loading Data.loadData(…) You may directly provide the HTML to be displayed by the browser ( such as a user manual for instance, directions on a map, or the actual app interface created as HTML instead of using the native Android UI framework ). package cis493.demoui; import android.os.Bundle; import android.app.Activity; import android.webkit.WebView; public class AndDemoUI extends Activity { WebView public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); browser.loadData(" Hello, world! ", "text/html", "UTF-8"); } Use same layout and manifest of previous example

package cis493.demoui; import... public class AndDemoUI extends Activity { WebView public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); // code your htlm in-line page (or store page in app’s "assets" folder) String aGoogleMap = "<img src=\" + "staticmap?center= , &zoom=14&size=300x300&sensor=false\"> "; String myHtmlPage = " Hello, world! " + " Greetings from Cleveland State University" + aGoogleMap + " "; browser.loadData(myHtmlPage, "text/html", "UTF-8"); } Android – UI – The WebKit Browser WebKit Browser 11 Loading Data.loadData(…) You may include simple static Google Maps

Android – UI – The WebKit Browser WebKit Browser 12 Browser Commands There is no navigation toolbar with the WebView widget (saving space). You could supply the UI –such as a Menu– to execute the following operations: reload() to refresh the currently-viewed Web page goBack() to go back one step in the browser history, and canGoBack() to determine if there is any history to trace back goForward() to go forward one step in the browser history, and canGoForward() to determine if there is any history to go forward to goBackOrForward() to go backwards or forwards in the browser history, where negative/positive numbers represent a count of steps to go canGoBackOrForward() to see if the browser can go backwards or forwards the stated number of steps (following the same positive/negative convention as goBackOrForward()) clearCache() to clear the browser resource cache and clearHistory() to clear the browsing history

Android – UI – The WebKit Browser WebKit Browser 13 Using our running example: browser.goBack(); browser.goForward(); browser.goBackOrForward(-2); browser.goBackOrForward(+2); browser.canGoBack(); browser.canGoForward(); browser.canGoBackOrForward(-2); browser.canGoBackOrForward(+2); browser.clearCache(true); browser.clearHistory(); browser.stopLoading();

Android – UI – The WebKit Browser WebKit Browser 14 Combining HTML + JAVASCRIPT + ANDROID public void addJavascriptInterface ( Object obj, String interfaceName ) Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript. IMPORTANT: Using addJavascriptInterface() allows JavaScript to control your application. This can be a very useful feature or a dangerous security issue. Do not use addJavascriptInterface() unless all of the HTML in this WebView was written by you. WARNING : This feature was ignored/broken (?) in version 2.3. A solution is expected from Android Development Team as of Sept See page:

Android – UI – The WebKit Browser WebKit Browser 15 Combining HTML + JAVASCRIPT + ANDROID Advantages offered by Android Development 1.Access to native services on the device, including location services 2.Placement in the Android Market 3.Rapid development using the Android SDK and Eclipse. Advantages offered by Google Maps API 1.Application exists in a server not inside a device. 2.Rapid versioning, removing the requirement for your users to download and install constant updates. 3.More frequent feature additions and bug fixes from Google. 4.Cross-platform compatibility: Using the Maps API allows you to create a single map that runs on multiple platforms. 5.Designed to load fast on Android and iPhone devices.

Android – UI – The WebKit Browser WebKit Browser 16 Combining HTML + JAVASCRIPT + ANDROID Learning Strategy WebView2: Passing Objects between Android and JS (goal: create interconnectivity) WebView3: Mapping a fixed location using Google Maps V3 (Pure HTML + JS, just update the server -no need to upgrade ALL devices carrying the application, portability, homogeneous design) WebView4: Passing a real location object to JS – draw a map centered at given location (mapping current location, combines two above).

Android – UI – The WebKit Browser WebKit Browser 17 HTML + JAVASCRIPT + ANDROID Exchanging objects between Android & JS Android OS locater object HTML You pass an object whose methods you want to expose to JavaScript (class vars not visible)

Android – UI – The WebKit Browser WebKit Browser 18 Part1. WebView2: Passing Objects between Android and JS

Android – UI – The WebKit Browser WebKit Browser 19 Part1. WebView2: Passing Objects between Android and JS <LinearLayout xmlns:android=" /android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <WebView android:layout_width="fill_parent" android:layout_height="fill_parent"/> Putting the pieces together: 1.Place a WebView in the main.xml file 2.Place html page in the assets folder 3.Create the Java object to share with JS Warning: tested on Android 2.2

Android – UI – The WebKit Browser WebKit Browser 20 Part1. WebView2: Passing Objects between Android and JS Android_Passing_HTML_JS function whereami() { // html asks android to provide data using object's GET methods document.getElementById("lat").innerHTML=locater.getLatitude(); document.getElementById("lon").innerHTML=locater.getLongitude(); document.getElementById("myText").value = locater.getCommonData(); } function talkBack2Android() { // bridge object used to send local (html) data to android app locater.setCommonData("Greetings from html"); var spyHtml = "Spy data coming from HTML\n" + "\n" + document.getElementById("myText").value + "\n" + document.getElementById("lat").innerHTML + "\n" + document.getElementById("lon").innerHTML; locater.htmlPassing2Android(spyHtml); } You are at Latitude (unknown) Longitude (unknown) Click to Get Location Enter some data here

Android – UI – The WebKit Browser WebKit Browser 21 Part1. WebView2: Passing Objects between Android and JS public class Main extends Activity { private WebView browser; MyLocater locater = new MyLocater(); Location public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); // get a location fix (lat, lon) mostRecentLocation = fakeGetLocation(); // set up the webview to show location results browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.addJavascriptInterface(locater, "locater"); browser.loadUrl("file:///android_asset/my_local_page1.html"); } private Location fakeGetLocation() { // faking the obtaining of a location object (discussed later!) Location fake = new Location("fake"); fake.setLatitude( ); fake.setLongitude( ); return fake; }

Android – UI – The WebKit Browser WebKit Browser 22 Part1. WebView2: Passing Objects between Android and JS // "MyLocater" is used to pass data back and forth between Android and JS code-behind public class MyLocater { private String commonData = "XYZ"; public double getLatitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLatitude(); } public double getLongitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLongitude(); } public void htmlPassing2Android(String dataFromHtml) { Toast.makeText(getApplicationContext(), "1\n" + commonData, 1).show(); commonData = dataFromHtml; Toast.makeText(getApplicationContext(), "2\n" + commonData, 1).show(); } public String getCommonData(){ return commonData; } public void setCommonData(String actualData){ commonData = actualData; } }//MyLocater }

Android – UI – The WebKit Browser WebKit Browser 23 Part2. WebView3: Using Google Maps V3 Webpage “webview_map.html” showing a Google map centered around Cleveland State University, Ohio (seen with IExplorer running in a Windows machine) Link:

html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } <script type="text/javascript" src=" function initialize() { var latlng = new google.maps.LatLng( , ); var myOptions = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } Android – UI – The WebKit Browser WebKit Browser 24 Part2. WebView3: Passing Objects between Android and JS This is the web page: webview_map.html

Android – UI – The WebKit Browser WebKit Browser 25 Part2. WebView3: Porting to Android the Google Map V3 App. <LinearLayout xmlns:android=" /android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <WebView android:layout_width="fill_parent" android:layout_height="fill_parent"/> Putting the pieces together: 1.Place a WebView in the main.xml file 2.Place html page in the assets folder 3.Add permission requests to manifest 4.Connect to Java code Warning: tested on Android 2.2

Android – UI – The WebKit Browser WebKit Browser 26 Part2. WebView3: Porting to Android the Google Map V3 App. Add the following permission requests to the AndroidManifest.xml file Map image shown on an Android device

Android – UI – The WebKit Browser WebKit Browser 27 Part2. WebView3: Porting to Android the Google Map V3 App. public class Main extends Activity { WebView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // connect browser to local html file showing map browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.loadUrl("file:///android_asset/webview_map.html"); }

Android – UI – The WebKit Browser WebKit Browser 28 Part3. WebView4: Android & Google Map V3 App (real locations) This experience combines the two previous examples: The goal is to use an Android object to pass ‘real location’ data to an html webpage. The page contains a JavaScript fragment to draw a map centered on the given coordinates. Warning: Make sure your target is: Google APIs (API Level 8) or higher. Latitude and longitude detected by the device. Image taken from an Android phone.

Android – UI – The WebKit Browser WebKit Browser 29 Part2. WebView3: Porting to Android the Google Map V3 App. <LinearLayout xmlns:android=" /android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <WebView android:layout_width="fill_parent" android:layout_height="fill_parent"/> Putting the pieces together: 1.Place a WebView in the main.xml file 2.Place html page in the assets folder 3.Add permission requests to manifest 4.Connect to Java code Warning: tested on Android 2.2

Android – UI – The WebKit Browser WebKit Browser 30 Part3. WebView4: Android & Google Map V3 App (real locations) Google Maps JavaScript API v3 Example: Marker Simple html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } function initialize() { //var myLatlng = new google.maps.LatLng( , ); var myLatlng = new google.maps.LatLng(locater.getLatitude(), locater.getLongitude()); var myOptions = { zoom: 17, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map }); } Html page creates a map using ‘real’ coordinates passed in the ‘locater’ object

Android – UI – The WebKit Browser WebKit Browser 31 Part3. WebView4: Android & Google Map V3 App (real locations) public class Main extends Activity implements LocationListener { private static final String MAP_URL = " samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html"; private WebView browser; //Location mostRecentLocation; LocationManager locationManager; MyLocater locater = new protected void onDestroy() { super.onDestroy(); // cut location service requests locationManager.removeUpdates(this); } private void getLocation() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // use GPS (you must be outside) //criteria.setAccuracy(Criteria.ACCURACY_COARSE); // towers, wifi String provider = locationManager.getBestProvider(criteria, true); // In order to make sure the device is getting the location, request // updates [wakeup after changes of: 1 sec. or 0 meter] locationManager.requestLocationUpdates(provider, 1, 0, this); locater.setNewLocation(locationManager.getLastKnownLocation(provider)); }

Android – UI – The WebKit Browser WebKit Browser 32 Part3. WebView4: Android & Google Map V3 App (real public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); getLocation(); setupbrowser(); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } /** Sets up the browser object and loads the URL of the page **/ private void setupbrowser() { final String centerURL = "javascript:centerAt(" + locater.getLatitude() + "," + locater.getLongitude() + ")"; // set up the browser to show location results browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.addJavascriptInterface(locater, "locater"); browser.loadUrl("file:///android_asset/webview_map.html");

Android – UI – The WebKit Browser WebKit Browser 33 Part3. WebView4: Android & Google Map V3 App (real locations) // Wait for the page to load then send the location information browser.setWebViewClient(new WebViewClient() public void onPageFinished(WebView view, String url) { browser.loadUrl(centerURL); } }); public void onLocationChanged(Location location) { String lat = String.valueOf(location.getLatitude()); String lon = String.valueOf(location.getLongitude()); Toast.makeText(getApplicationContext(), lat + "\n" + lon, 1).show(); locater.setNewLocation(location); public void onProviderDisabled(String provider) { // needed by Interface. Not used public void onProviderEnabled(String provider) { // needed by Interface. Not used public void onStatusChanged(String provider, int status, Bundle extras) { // needed by Interface. Not used }

Android – UI – The WebKit Browser WebKit Browser 34 Part3. WebView4: Android & Google Map V3 App (real locations) // /////////////////////////////////////////////////////////////////// // An object of type "MyLocater" will be used to pass data back and // forth between the Android app and the JS code behind the html page. // /////////////////////////////////////////////////////////////////// public class MyLocater { private Location mostRecentLocation; public void setNewLocation(Location newCoordinates){ mostRecentLocation = newCoordinates; } public double getLatitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLatitude(); } public double getLongitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLongitude(); } }// MyLocater }//class

Android – UI – The WebKit Browser WebKit Browser 35 Where to go next? Google Maps API Family Google Maps API – Webservices Google Maps JavaScript API V3 Questions ?