Thông tin tài liệu
10/4/2011
1
10
Android
TheWebKit Browser
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers
http://developer.android.com/index.html
GoogleMapsJavascript APIV3Basics
http://code.google.com/apis/maps/documentation/javascript/basics.html
TheBusyCoder'sGuidetoAndroidDevelopment
byMarkL.Murphy
Copyright©2008‐2009CommonsWare,LLC.
ISBN:978‐0‐9816780‐0‐9
10.Android–UI–TheWebKit Browser
WebKit Browser
• InAndroidyoucanembedthebuilt‐inWebbrowserasawidget
inyourownactivities,fordisplayingHTMLmaterialorperform
Internetbrowsin
g
.
g
• TheAndroidbrowserisbasedonWebKit,thesameenginethat
powersApple'sSafariWeb browser.
• AndroidusestheWebView widgettohostthebrowser’spages
22
• ApplicationsusingtheWebView com ponentmustrequest
INTERNET permission.
10/4/2011
2
10.Android–UI–TheWebKit Browser
WebKit Browser
BrowsingPower
ThebrowserwillaccesstheInternetthroughwhatevermeans
are available to that specific device at the present time (
WiFi
are
available
to
that
specific
device
at
the
present
time
(
WiFi
,
cellularnetwork,Bluetooth‐tetheredphone,etc.).
TheWebKit renderingengineusedtodisplaywebpagesincludes
methodsto
1. navi
g
ateforwardandbackwardthrou
g
hahistor
y,
33
g g y,
2. zoominandout,
3. performtextsearches,
4. loaddata
5. stoploadingand
6. more.
10.Android–UI–TheWebKit Browser
WebKit Browser
Warning
InorderforyourActivitytoaccesstheInternetandloadwebpages
inaWebView,youmustaddtheINTERNET permissionstoyou r
AndroidManifestfile:
<uses-permission android:name="android.permission.INTERNET" />
Thi t b hild f th <
if t
> lt
44
Thi
smus
t
b
eac
hild
o
f
th
e
<
man
if
es
t
>
e
l
emen
t
.
(seenextexample)
10/4/2011
3
10.Android–UI–TheWebKit Browser
WebKit Browser
Example:Asimplebrowsingexper ience
Let’sgoe‐shopping
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/webkit"
android:la
y
out width
=
"
f
ill
p
arent
"
55
y_
_p
android:layout_height="fill_parent"
/>
</LinearLayout>
package
cis493 demoui;
10.Android–UI–TheWebKit Browser
WebKit Browser
Example:Asimplebrowsingexper ience
Let’sgoe‐shopping
package
cis493
.
demoui;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
public class AndDemoUI extends Activity {
WebView browser;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
browser=(WebView)findViewById(R.id.webkit);
browser.loadUrl("http://eBay.com");
browser.getSettings().setJavaScriptEnabled(true);
}
}
66
Thisappis
hard‐wir edto
eBay
10/4/2011
4
<?
xml
version
=
"
10
"
encoding
=
"utf
-
8
"
?>
10.Android–UI–TheWebKit Browser
WebKit Browser
Example:Asimplebrowsingexper ience
Let’sgoe‐shopping‐ Manifest
<?
xml
version
=
1
.
0
encoding
=
utf
-
8
?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.demoui" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndDemoUI" android:label="@string/app_name">
<intent-filter>
i
i
ii i
/
<act
i
on andro
i
d:name
=
"
a
ndro
i
d.
i
ntent.act
i
on.MAIN
"
/
>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
77
10.Android–UI–TheWebKit Browser
WebKit Browser
Warning
If you set the URL to a site whose pages depend on
Javascript
you
If
you
set
the
URL
to
a
site
whose
pages
depend
on
Javascript
you
mayseeanempty,whitescreen.
Bydefault Javascript isturnedoff inWebView widgets.
IfyouwanttoenableJavascript,call:
88
myWebView.setSettings().setJavaScriptEnabled(true);
ontheWebView instance.
Tobediscussedlaterinthischapter.
10/4/2011
5
10.Android–UI–TheWebKit Browser
WebKit Browser
Warning
UnderSDK1.5aWebView hasabuilt‐in OptionMenu
99
UsingGo option UsingMoreoption
10.Android–UI–TheWebKit Browser
WebKit Browser
LoadingData.loadData(…)
YoumaydirectlyprovidetheHTMLtobedisplayedbythebrowser
(
such as a user manual for instance directions on a map or the actual app
(
such
as
a
user
manual
for
instance
,
directions
on
a
map
,
or
the
actual
app
interfacecreatedasHTMLinsteadofusingthenativeAndroidUIframework
).
package cis493.demoui;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
public class AndDemoUI extends Activity {
WebView browser;
@O id
1010
@O
verr
id
e
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
browser=(WebView)findViewById(R.id.webkit);
browser.loadData("<html><body>Hello, world!</body></html>",
"text/html",
"UTF-8");
}
}
Usesamelayoutandmanifest
ofpreviousexample
10/4/2011
6
package
cis493 demoui;
10.Android–UI–TheWebKit Browser
WebKit Browser
LoadingData.loadData(…)
Youmayincludesimplestatic GoogleMaps
package
cis493
.
demoui;
import . . .
public class AndDemoUI extends Activity {
WebView browser;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
browser=(WebView)findViewById(R.id.webkit);
//codeyourhtlm in‐linepage(orstorepageinapp’s"assets"folder)
StringaGoogleMap ="<img src=\"http://maps.googleapis.com/ma ps/api/"
+"staticmap?center=41.5020952,‐81.6789717 &zoom=14&size=300x300&sensor=false\">";
StringmyHtmlPage ="<html><body>Hello,world!"
+"<br>GreetingsfromClevelandStateUniversity"
+aGoogleMap
+"</body></html>";
browser.loadData(myHtmlPage,"text/html","UTF‐8");
}
}
1111
10.Android–UI–TheWebKit Browser
WebKit Browser
BrowserCommands
ThereisnonavigationtoolbarwiththeWebView widget(savingspace).
YoucouldsupplytheUI–suchasaMenu– toexecutethefollowingoperations:
• reload() torefresh thecurrently‐viewedWebpage
• goBack() togobackonestepinthebrowserhistory,andcanGoBack()todetermineif
thereisanyhistorytotraceback
• goForward() togoforwardonestepinthebrowserhistory,andcanGoForward()to
determineifthereisanyhistorytogoforwardto
• goBack OrForward() togobackwardsorforwardsinthebrowserhistory,where
negative/positive numbersrepresentacountofstepstogo
•
canGoBackOrForward
()
to see if the browser can go backwards or forwards the
1212
•
canGoBackOrForward
()
to
see
if
the
browser
can
go
backwards
or
forw ards
the
statednumberofsteps(followingthesamepositive/negativeconventionas
goBackOrForward())
• clearCache() toclearthebrowserresou rcecac heandclearHistory() toclearthe
browsinghistory
10/4/2011
7
10.Android–UI–TheWebKit Browser
WebKit Browser
Usingourrunningexample:
browser.
g
oBack
();
g
();
browser.goForward();
browser.goBackOrForward(-2);
browser.goBackOrForward(+2);
browser.canGoBack();
browser.canGoForward();
browser.canGoBackOrForward(-2);
1313
browser.canGoBackOrForward(+2);
browser.clearCache(true);
browser.clearHistory();
browser.stopLoading();
10.Android–UI–TheWebKit Browser
WebKit Browser
CombiningHTML+JAV ASCRIPT+ANDROID
publicvoidaddJavascriptInterface ( Objectobj,StringinterfaceName )
UsethisfunctiontobindanobjecttoJavaScriptsothatthemethods
canbeaccessedfromJavaScript.
IMPORTANT:
UsingaddJavascriptInterface()allowsJavaScripttocontrolyourapplication.
Thiscanbeaveryusefulfea tureoradangeroussecurityissue.
Donotuse
addJavascriptInterface()unlessalloftheHTMLinthisWebView
waswrittenbyyou.
1414
WARNING:
Thisfeaturewasignored/broken(?)inversion2.3.Asolutionis
expectedfromAndroidDevelopmentTeamasofSept2011.
Seepage:
http://quitenoteworthy.blogspot.com/2010/12/handling‐android‐23‐webviews‐broken.html
10/4/2011
8
10.Android–UI–TheWebKit Browser
WebKit Browser
CombiningHTML+JAV ASCRIPT+ANDROID
Ad t ff d b Ad idDl t
Ad
van
t
ageso
ff
ere
d
b
y
A
n
d
ro
id
D
eve
l
opmen
t
1. Accesstonativeservicesonthedevice,includinglocationser vices
2. PlacementintheAndroidMarket
3. RapiddevelopmentusingtheAndroidSDKandEclipse.
AdvantagesofferedbyGoogleMapsAPI
1. Applicationexis tsinaservernotinsideadevice.
2
id ii i h i f dld
1515
2
.Rap
id
vers
i
on
i
ng,remo v
i
ngt
h
erequ
i
rement
f
oryourusersto
d
own
l
oa
d
andinstallconstantupdates.
3. MorefrequentfeatureadditionsandbugfixesfromGoogle.
4. Cross‐platformcompatibility:UsingtheMapsAPIallowsyoutocreatea
singlemapthatrunsonmultipleplatforms.
5. Designedtoloadfast onAndroidandiPhonedevices.
10.Android–UI–TheWebKit Browser
WebKit Browser
CombiningHTML+JAVASCRIPT+ANDROID
LearningStrategy
• WebView2:PassingObjectsbetweenAndroidandJS
(goal:createinterconnectivity)
• WebView3:MappingafixedlocationusingGoogleMapsV3
(PureHTML+JS,justupdatetheserver‐noneedtoupgradeALLdevices
carryingtheapplication,portability,homogeneousdesign)
1616
• WebView4:PassingareallocationobjecttoJS–drawamapcenteredat
givenlocation(mappingcurrentlocation,combinestwoabove).
10/4/2011
9
10.Android–UI–TheWebKit Browser
WebKit Browser
HTML+JA VASCRIPT+ANDROID
ExchangingobjectsbetweenAndroid&JS
AndroidOS
HTML
1717
locater object
Youpassanobjectwhose
methods youwanttoexposeto
JavaScript (classvars notvisible)
10.Android–UI–TheWebKit Browser
WebKit Browser
Part1.WebView2: PassingObjectsbetweenAndroidandJS
1818
10/4/2011
10
10.Android–UI–TheWebKit Browser
WebKit Browser
Part1.WebView2: PassingObjectsbetweenAndroidandJS
Puttingthepiecestogether:
1. PlaceaWebView inthemain.xmlfile
2. Placehtml
p
a
g
eintheassets folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res
/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<
WbVi
pg
3. CreatetheJavaobject tosharewithJS
1919
<
W
e
bVi
ew
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Warning:testedonAndroid2.2
10.Android–UI–TheWebKit Browser
WebKit Browser
Part1.WebView2: PassingObjectsbetweenAndroidandJS
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Android_Passing_HTML_JS</title> <head>
<script language="javascript">
function whereami() {
// html asks android to provide data using object's GET methods
document.
g
etElementB
y
Id("lat").innerHTML
=
l
ocater.
g
etLatitude
(
);
gy
g
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);
}
</script>
</head>
<body>
<p> You are at </p>
<table border=
"
1
"
cellspacing
=
"
1
"
cellpadding
=
"
1
"
>
2020
<table
border= 1
cellspacing
=1
cellpadding
=1>
<tr>
<td bgcolor="#FFFFCC"> Latitude </td>
<td><span id="lat"> (unknown) </span></td>
</tr>
<tr>
<td bgcolor="#FFFFCC"> Longitude </td>
<td><span id="lon"> (unknown) </span></td>
</tr>
</table>
<p><a onClick="whereami()"><u> Click to Get Location </u></a></p>
<p> Enter some data here <input type="text" id="myText" />
<p> <input type="button" onclick= "talkBack2Android()" value="Talking to Android">
</body>
</html>
[...]... Map image shown on an Android device 26 13 10/4/2011 10. Android – UI – The WebKit Browser WebKit Browser Part2. WebView3:... android: orientation="horizontal" android: layout_width="fill_parent" android: layout_height="fill_parent"> Warning: tested on Android 2.2 29 10. Android – UI – The WebKit Browser WebKit Browser Part3. WebView4: Android & Google Map V3 App (real locations) ... }//MyLocater } 22 11 10/4/2011 10. Android – UI – The WebKit Browser WebKit Browser 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) 23 Link: http://code.google.com/apis/maps/documentation/javascript/basics.html 10. Android – UI – The WebKit Browser WebKit Browser Part2. WebView3:... eb e ); browser.getSettings().setJavaScriptEnabled(true); browser.loadUrl("file:// /android_ asset/webview_map.html"); } } 27 10. Android – UI – The WebKit Browser WebKit Browser Part3. WebView4: Android & Google Map V3 App (real locations) This experience combines the two previous examples: p • The goal is to use an Android object to pass ‘real location’ data to an html webpage. • The page contains a JavaScript fragment to ... 30 15 10/4/2011 10. Android – UI – The WebKit Browser WebKit Browser Part3. WebView4: Android & Google Map V3 App (real locations) public class Main extends Activity implements LocationListener { private static final String MAP_URL = "http://gmapssamples.googlecode.com/svn/trunk/articles -android- webmap/simple -android- map.html"; private WebView browser; //Location... draw a map centered on the given coordinates Latitude and longitude detected by the device Image taken from an Android phone Warning: Make sure your target is: Google APIs (API Level 8) or higher 28 14 10/4/2011 10. Android – UI – The WebKit Browser WebKit Browser Part2. WebView3: Porting to Android the Google Map V3 App Putting the pieces together: 1 Place a WebView in the main.xml file 2 Place html page in the assets... 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(9.938038); fake.setLongitude(-84.054430); return fake; } 21 10. Android – UI – The WebKit Browser WebKit Browser Part1. WebView2: Passing Objects between Android and JS // "MyLocater"
Ngày đăng: 16/03/2014, 23:37
Xem thêm: Android chapter10 webkit, Android chapter10 webkit