10/4/2011
1
10
Android
TheWebKit Browser
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers
/>GoogleMapsJavascript APIV3Basics
/>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=" />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("");
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=" />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=\" 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:
/>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=" />/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>
10/4/2011
11
10.Android–UI–TheWebKit Browser
WebKit Browser
Part1.WebView2: PassingObjectsbetweenAndroidandJS
public class Main extends Activity {
private WebView browser;
MyLocater locater = new MyLocater();
Location mostRecentLocation;
@Override
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);
b
ddJ i tI t f
(
lt
"l t "
)
2121
b
rowser.a
ddJ
avascr
i
p
tI
n
t
er
f
ace
(
l
oca
t
er
,
"l
oca
t
er
"
)
;
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;
}
10.Android–UI–TheWebKit Browser
WebKit Browser
Part1.WebView2: PassingObjectsbetweenAndroidandJS
// "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
;
2222
commonData
dataFromHtml
;
Toast.makeText(getApplicationContext(), "2\n" + commonData, 1).show();
}
public String getCommonData(){
return commonData;
}
public void setCommonData(String actualData){
commonData = actualData;
}
}//MyLocater
}
10/4/2011
12
10.Android–UI–TheWebKit Browser
WebKit Browser
Part2.WebView3: UsingGoogleMapsV3
Webpage“webview_map.html”showingaGooglemap centeredaround
ClevelandStateUniversity,Ohio(seenwithIExplorer runninginaWindows
machine)
2323
Link: ation/javascript/basics.html
<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="initial‐scale=1.0,user‐scalable=no"/>
10.Android–UI–TheWebKit Browser
WebKit Browser
Part2.WebView3: PassingObjectsbetweenAndroidandJS
Thisisthewebpage:
webview_map.html
<styletype="text/css">
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#map_canvas {height:100%}
</style>
<scripttype="text/javascript"
src=" /></script>
<scripttype="text/javascript">
functioninitialize(){
var latlng =newgoogle.maps.LatLng(41.5020952,‐81.6789717);
var myOptions ={
zoom:15,
center:
latlng
center:
latlng
,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=newgoogle.maps.Map(document.getElementById("map_canvas"),myOptions);
}
</script>
</head>
<bodyonload="initialize()">
<divid="map_canvas"style="width:100%;height:100%"></div>
</body>
</html>
2424
10/4/2011
13
10.Android–UI–TheWebKit Browser
WebKit Browser
Part2.WebView3: PortingtoAndroidtheGoogleMapV3App.
Puttingthepiecestogether:
1. PlaceaWebView inthemain.xmlfile
2. Placehtml
p
a
g
eintheassets folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=" />/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<
WbVi
pg
3. Addpermission requeststomanifest
4. ConnecttoJavacode
2525
<
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
Part2.WebView3: PortingtoAndroidtheGoogleMapV3App.
AddthefollowingpermissionrequeststotheAndroidManifest.xmlfile
<uses-permission android:name="android.permission.INTERNET"/>
<
uses
permission
android:name
=
"
android permission ACCESS COARSE LOCATION
"
/>
<
uses
-
permission
android:name
=
"
android
.
permission
.
ACCESS_COARSE_LOCATION
"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MapimageshownonanAndroiddevice
2626
10/4/2011
14
10.Android–UI–TheWebKit Browser
WebKit Browser
Part2.WebView3: PortingtoAndroidtheGoogleMapV3App.
public
class
Main
extends
Activity {
public
class
Main
extends
Activity
{
WebView browser;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// connect browser to local html file showing map
b
r
o
w
se
r =
(
W
eb
Vi
e
w
)
f
in
d
Vi
e
wB
y
I
d
(
R
.i
d
.
web
vi
e
w
);
2727
bose
(
eb e
)
deyd
(
d
eb e
);
browser.getSettings().setJavaScriptEnabled(true);
browser.loadUrl("file:///android_asset/webview_map.html");
}
}
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
Thisexperiencecombinesthetwoprevious
exam
p
les:
p
• ThegoalistouseanAndroidobjecttopass
‘reallocation’datatoanhtmlwebpage.
• ThepagecontainsaJavaScriptfragmentto
drawamapcenteredonthegiven
coordinates.
2828
Warning:Makesureyourtargetis:GoogleAPIs(APILevel8)orhigher.
Latitudeandlongitudedetectedbythedevice.
ImagetakenfromanAndroidphone.
10/4/2011
15
10.Android–UI–TheWebKit Browser
WebKit Browser
Part2.WebView3: PortingtoAndroidtheGoogleMapV3App.
Puttingthepiecestogether:
1. PlaceaWebView inthemain.xmlfile
2. Placehtml
p
a
g
eintheassets folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=" />/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<
WbVi
pg
3. Addpermission requeststomanifest
4. ConnecttoJavacode
2929
<
W
e
bVi
ew
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Warning:testedonAndroid2.2
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="initial‐scale=1.0,user‐scalable=no"/>
<meta http
‐
equiv=
"
content
‐
type
"
content=
"
text/html;
charset
=UTF
‐
8
"
/>
Html
p
a
g
ecreatesama
p
<meta
http
equiv= content
type
content= text/html;
charset
=UTF
8/>
<title>GoogleMapsJavaScriptAPIv3Example:MarkerSimple</title>
<styletype="text/css">
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#map_canvas {height:100%}
</style>
<scripttype="text/javascript"src=" /><scripttype="text/javascript">
functioninitialize(){
//var myLatlng =newgoogle.maps.LatLng(41.5020952,‐81.6789717);
var myLatlng =newgoogle.maps.LatLng(locater.getLatitude(),locater.getLongitude());
var myOptions ={
zoom:17,
center:myLatlng,
TId
l M T Id ROADMAP
pg p
using‘real’coordinates
passedinthe‘locater’
object
3030
map
T
ype
Id
:goog
l
e.maps.
M
ap
T
ype
Id
.
ROADMAP
}
var map=newgoogle.maps.Map(document.getElementById("map_canvas"),myOptions);
var marker=newgoogle.maps.Marker({
position:myLatlng,
map:map
});
}
</script>
</head>
<bodyonload="initialize()">
<divid="map_canvas"></div>
</body>
</html>
10/4/2011
16
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
public class Main extends Activity implements LocationListener {
private static final String MAP_URL = "http://gmaps-
samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
private WebView browser;
//Location mostRecentLocation;
LocationManager locationManager;
MyLocater locater = new MyLocater();
@Override
protected void onDestroy() {
super.onDestroy();
// cut location service requests
locationManager.removeUpdates(this);
}
private void getLocation() {
locationManager
=(
LocationManager
)
getSystemService
(
Context
LOCATION SERVICE
);
3131
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));
}
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
m
ain
)
;
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() + ")";
3232
// 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");
10/4/2011
17
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
// Wait for the page to load then send the location information
browser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished
(
WebVie
w
v
iew, String
u
rl
)
{
browser.loadUrl(centerURL);
}
});
}
@Override
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);
}
@Override
3333
@Override
public void onProviderDisabled(String provider) {
// needed by Interface. Not used
}
@Override
public void onProviderEnabled(String provider) {
// needed by Interface. Not used
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// needed by Interface. Not used
}
10.Android–UI–TheWebKit Browser
WebKit Browser
Part3.WebView4: Android&GoogleMapV3App(reallocations)
// ///////////////////////////////////////////////////////////////////
// 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();
}
3434
public double getLongitude() {
if (mostRecentLocation == null) return (0);
else return mostRecentLocation.getLongitude();
}
}// MyLocater
}//class
10/4/2011
18
10.Android–UI–TheWebKit Browser
WebKit Browser
Wheretogonext?
GoogleMapsAPIFamily
/>GoogleMapsAPI– Webservices
/>GoogleMapsJavaScriptAPIV3
/>353535
Questions?