Professional Documents
Culture Documents
lập trình phonegap cho người mới học
lập trình phonegap cho người mới học
MC LC
LI NI U ........................................................................................................................ 5
Cc ti liu lin quan ............................................................................................................. 6
I.Events................................................................................................................................. 7
1.1.Hiu thm v events .................................................................................................... 7
1.2.Cch s dng EVENTS LISTENER............................................................................. 8
1.3.Hiu thm v cc dng s kin EVENT TYPES .......................................................... 9
1.3.1.Backbutton ............................................................................................................ 9
1.3.2.Deviceready ........................................................................................................ 10
1.3.3.Menubutton ......................................................................................................... 11
1.3.4.Pause.................................................................................................................. 12
1.3.5.Resume .............................................................................................................. 13
1.3.6.Searchbutton....................................................................................................... 14
1.3.7.Online ................................................................................................................. 15
1.3.8.Offline ................................................................................................................. 16
1.3.9.Mt v d n gin v s phn hi li cc s kin events .................................. 17
1.3.10.Mt v d n gin v vic phn hi li cc s kin Button Events ................... 18
II.Cch lm vic vi thit b, mng network, v cc thng bo notifications ......................... 20
2.1.Cch ly thng tin t thit b ...................................................................................... 20
2.1.2.Cch ly v tn ca thit b Device Name ........................................................... 20
2.1.3.Cch ly v thng tin phin bn phonegap.......................................................... 21
2.1.4.Cch ly v nn tng thit b Device Platform ..................................................... 21
2.1.5.Cch ly v ID quc t ca thit b UUID ............................................................ 21
2.1.6.Cch ly v thng tin phin bn h iu hnh ..................................................... 22
2.1.7.V d v cch ly thng tin ca thit b ................................................................ 22
2.2.Cch kim tra 1 mng network .................................................................................. 23
Cch xc nh dng kt ni .......................................................................................... 24
2.3.Cch s dng cc thng bo NOTIFICATIONS......................................................... 26
2.3.1.Cch s dng Alerts ........................................................................................... 26
2.3.2.Cch s dng hp thoi tng tc Confirmation Dialogs .................................... 27
2.3.3.Cch s dng Beeps .......................................................................................... 28
2.3.4.Cch s dng ch rung Vibrations ................................................................. 29
2.3.5.V d v cch s dng tt c 4 loi thng bo Notifications ................................ 29
III.Gia tc k Accelerometer ................................................................................................ 32
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
LI NI U
1 im c nhn mnh rt thch Phonegap, chnh l tnh n gin v hu nh
khng c tnh rng buc. Phonegap c gi l framework tuy nhin n khng ging nh 1
vi framework PHP m mnh tng hc, vi nhng framework PHP ny, n nh ngha li
hon ton cch bn vit m code, v n i hi bn phi hiu r su rng v cc thnh
phn h thng bn trong, th bn mi c th lp trnh thng tho c. Vi Phonegap, n
khng km kp bn vo trong 1 h thng c 1 quy chun ring ri rm no c, bn c th t
do thoi mi lp trnh theo cch m bn mun (tuy nhin ci g cng c 2 mt ca n), bn
ch cn nm bt 1 cng ngh duy nht - cng ngh nn Web(bao gm HTML5, Javascript,
CSS), b qua gnh nng cn phi nm bt v hiu r v cc cng ngh bn trong mi nn
tng (Android, iOS, Blackberry, Windowphone, ) m bn vn c th to ra c cc ng
dng vit mt ln, bin dch qua cloud v chy khp ni tng thch vi hu ht cc nn
tng h iu hnh di ng hin ti.
Ti liu c vit ging nh 1 bn ghi chp, ghi li nhng th m mnh c c t cc
ebook ting anh, do vy b cc sp xp ca n c th cha chnh xc, cch trnh by khng
theo chun 1 ebook no c v nhiu ch vit cha r ngha v khng mch lc do hn ch
v ngoi ng ca bn thn mnh. Ti liu mang m tnh cht c nhn do vy bn s bt
gp trong ti liu ny nhiu on k t in m, in mu, c ch ln bt thng v c t
mu khc nhau - l cc on c lin quan n nhau hay l nhng ghi ch quan trng m
bn cn phi c k.
Ni dung trong ti liu ny c da trn cc cun ebook: Beginning Phonegap Thomas Myer, PhoneGap Essentials - John M. Wargo,
Apache Cordova Documentation 2.2.0 Phonegap team, v 1 s gii thch, nh ngha
v kin trc ca HTML5 t W3C.org. Ti liu ny khng cp ti y cc hm APIs
c Phonegap h tr. C th, cc phn sau b lc b: Capture, Compass, Contacts,
Globalization, Guides (do mnh khng c thi gian vit nt, v mnh cng khng s
dng n cc phn b lc b ny)
Nu c thc mc hay gp g, cc bn c th ng k ngay 1 nick vo din n
www.phonegap.vn/forum t cu hi trc tip, cc MOD v ADMIN s tr li cu hi
ca bn trong thi gian sm nht.
I.Events
1 s kin events trong phonegap tng i ging s kin trong javascript.1 hnh ng (thao
tc) c thc hin trn thit b - v d nh document object model (DOM) c ti xong
v do thit b trng thi sn sng ready - v hin ti phonegap c th thc hin 1 vi
th tr li(p ng) li s kin ny
deviceready
pause
resume
online
offline
backbutton
batterycritical
batterylow
batterystatus
menubutton
searchbutton
startcallbutton
endcallbutton
volumedownbutton
volumeupbutton
trong tt c cc s kin events trn th s kin deviceready l quan trng nht m ta phi
xem xt ti.khng c n th ng dng ca ta s khng bit khi no phonegap c load
hon ton.khi n c kch hot, ta c th gi 1 cch an ton bt c cc hm PhoneGap
function no v do c th ln lt truy cp an ton vo cc API bn a
khi s kin deviceready event c kch hot, th ta bit c 2 iu : DOM c load,
v do vy c PhoneGap API
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap backbutton Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady()
}
// Handle the back button
//
function onBackButton() {
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
1.3.2.Deviceready
Nh nhc n t trc, s kin deviceready l s kin quan trng nht m ta c th
xc nh.theo ta cn phi xc nh s kin ny u tin trc khi ta lm bt c nhng g
khc bi v khi n c kch hot th ng ngha vi vic ta chc chn gi c cc
PhoneGap API
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady(){
//ready!
}
dnh cho nhng ngi pht trin trn BlackBerry OS 4.6, th RIM Browserfield khng
h tr hm s kin event ny, nn ta cn s dng PhoneGap.available thay th nh
sau :
function onLoad() {
var intervalID = window.setInterval(
function() {
if (PhoneGap.available) {
window.clearInterval(intervalID);
onDeviceReady();
}
},
500
);
}
function onDeviceReady() {
// use the phonegap api!
}
10
1.3.3.Menubutton
S kin menubutton c kch hot khi ngi dung n vo nt Menu trn thit b android
xc nh s kin ny, th ta cn ng k 1 event listener nh sau :
document.addEventListener(menubutton, onMenuButton, false);
function onMenuButton(){
//handle the menu button
}
Cng ging nh cc events khc, ta khng nn ng k kiu nh th ny cho ti khi ta xc
nh c s kin deviceready
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap menubutton Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady()
}
// Handle the menu button
//
function onMenuButton() {
}
</script>
</head>
<body>
</body>
</html>
11
1.3.4.Pause
Khi s kin pause c kch hot l khi 1 ng dng c t vo ch chy nn
xc nh s ki ny, ta ng k 1 event listener nh sau :
document.addEventListener(pause, onPause, false);
function onPause(){
//handle the pause event
}
Hay ta lm theo nh ng tiu chun ging nh trn nh sau :
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap pause Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady() {
// Register the event listener
document.addEventListener(pause, onPause, false);
}
// Handle the pause
//
function onPause() {
}
</script>
</head>
<body>
</body>
</html>
12
1.3.5.Resume
S kin resume c kch hot khi 1 ng dng ang trng thi tm dng (chy nn)
c kch hot tr li lm vic
xc nh s ki ny, ta ng k 1 event listener nh sau :
document.addEventListener(resume, onResume, false);
function onResume(){
//handle the resume event
}
Cng ging nh cc events khc, ta khng nn ng k kiu nh th ny cho ti khi ta xc
nh c s kin deviceready
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap resume Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady() {
// Register the event listener
document.addEventListener(resume, onResume, false);
}
// Handle the resume
//
function onResume() {
}
</script>
</head>
<body>
</body>
</html>
13
1.3.6.Searchbutton
S kin searchbutton c kch hot khi ngi dng n vo nt Search trn thit b android
xc nh s ki ny, ta ng k 1 event listener nh sau :
document.addEventListener(searchbutton, onSearchButton, false);
function onSearchButton(){
//handle the search button
}
Cng ging nh cc events khc, ta khng nn ng k kiu nh th ny cho ti khi ta xc
nh c s kin deviceready
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap searchbutton Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady() {
// Register the event listener
document.addEventListener(searchbutton, onSearchButton, false);
}
// Handle the search button
//
function onSearchButton() {
}
</script>
</head>
<body>
</body>
</html>
14
1.3.7.Online
S kin online c kch hot khi 1 ng dng phonegap ang online (iu ny c ngha l
n ang c kt ni internet).y l 1 s kin mi c thm vo trong phin bn 0.9.6 v
n ch c h tr trn cc thit b iOS, Android, and BlackBerry
xc nh s ki ny, ta ng k 1 event listener nh sau :
document.addEventListener(online, isOnline, false);
function isOnline(){
//handle the online event
}
Cng ging nh cc events khc, ta khng nn ng k kiu nh th ny cho ti khi ta xc
nh c s kin deviceready
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap online Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady() {
// Register the event listener
document.addEventListener(online, isOnline, false);
}
// Handle the online event
//
function isOnline() {
}
</script>
</head>
<body>
</body>
</html>
15
1.3.8.Offline
S kin offline c kch hot khi 1 ng dng phonegap ang offline (iu ny c ngha l
n khng kt ni internet).y l 1 s kin mi c thm vo trong phin bn 0.9.6 v n
ch c h tr trn cc thit b iOS, Android, and BlackBerry
xc nh s ki ny, ta ng k 1 event listener nh sau :
document.addEventListener(offline, isOffline, false);
function isOffline(){
//handle the offline event
}
16
}
// Handle the pause
//
function onPause() {
alert(Paused!);
}
// Handle the resume
//
function onResume() {
alert(Resumed!);
}
</script>
</head>
<body>
</body>
</html>
17
}
// Handle the backbutton
//
function onBackButton() {
alert(You hit the back button!);
}
// Handle the menubutton
//
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
18
19
device.uuid s id ca thit b
tn ca thit b device
phin bn phonegap
20
android
blackberry
iphone
webOS
21
22
23
Cch xc nh dng kt ni
xc nh dng ca kt ni mng network th ta s phi s dng connection.type nh
sau :
function checkConnection(){
var myState = navigator.network.connection.type;
//return a specific state
}
UNKNOWN
ETHERNET
WIFI
CELL_2G
CELL_3G
CELL_4G
NONE
24
<!DOCTYPE html>
<html>
<head>
<title>Connectivity Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = Unknown connection;
states[Connection.ETHERNET] = Ethernet connection;
states[Connection.WIFI] = WiFi connection;
states[Connection.CELL_2G] = Cell 2G connection;
states[Connection.CELL_3G] = Cell 3G connection;
states[Connection.CELL_4G] = Cell 4G connection;
states[Connection.NONE] = No network connection;
alert(Connection type: + states[networkState]);
}
</script>
</head>
<body>
<p>A dialog box will report the network state.</p>
</body>
</html>
25
Alerts
Confirmation dialogs
Beeps
Vibrations
26
27
navigator.notification.beep(2);
hm ny cn 1 tham s truyn vo, n l 1 kiu int dng xc nh s ting beep m ta
mun pht
hm ny c h tr trong cc thit b Android, BlackBerry, webOS, v iPhone
28
29
30
31
III.Gia tc k Accelerometer
3.1.Th no l gia tc k Accelerometer ?
gia tc k Accelerometer l 1 thit b dng ghi li chuyn ng trong khng gian 3 chiu
XYZ
hnh dung c 3 chiu XYZ, th ta t thit b ln trn 1 b mt phng ging nh trn
mt bn.ta gi s rng b mt ny c rt t ma st v v d nh ta c th t thit b sang
tri v sang phi m khng cn phi nng n ln.mc ch ca v d ny l gip ta hnh
dung c ni ta t thit b ti v tr (0,0,0) trong khng gian ta .bt c cch no m ta
dng di chuyn thit b th s dn n 1 s thay i trong h ta
nu thit b l mng nm trn mt bn v khi ta di chuyn n sang tri hay sang phi th
chnh l ta di chuyn n dc theo trc X.ta di chuyn n sang tri l ta cho n 1 kt qu m,
v ta di chuyn n sang phi th ta cho n kt qu dng.nu ta di chuyn thit b ra xa bn
hay ti gn ch ta th chnh l ta ang di chuyn n trn trc Y.nu di chuyn n ra xa th ta
c kt qu dng theo trc Y, v nu di chuyn n li gn th ta c kt qu m
trc Z c miu t l chiu ln xung v c thm vo lm chiu th 3 ca h trc ta
.nu ta cm ly thit b v cm n tin n mt th ta c kt qu dng theo trc Z.nu
ta cho thit b xung di mt bn th ta c kt qu m theo trc Z
tt nhin rt l kh khn khi ta dch chuyn 1 thit b theo ch 1 trc m khng gy nh
hng ti cc trc khc.nu ta cm thit b ln ( v nh di chuyn n ti gn mt) th ta nhn
c kt qu dng i vi trc Z, nhng cng ging nh vy khi ta mang n gn c th
hn th thu c kt qu m theo trc Y
gi hnh dung xem, chuyn g s xy ra nu ta tung thit b quay tr li b mt bn - nh
ng tung qu mnh ta c th lm v n.khi gia tc k accelerometer bn trong thit b
s xc nh tt c chuyn ng dc theo trc XYZ
32
1 game kh ph bin khc l Super Monkey Ball nh trong hnh 6-2. tng nm ng
sau game ny l hng dn 1 ch kh nh d thng vt qua cc chng ngi vt khc
nhau bng cch nghing hay lc iphone
33
Trn thit b android, ta cng c Hyperspace nh trong hnh 6-3, trong ta s dng
nghing hay chuyn ng iu khin 1 tri bng i xuyn qua cc chng ngi vt.
34
35
36
37
function onSuccess(acceleration)
}
function onError() {
alert(oooops!);
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
38
watchID = navigator.accelerometer.watchAcceleration(onSuccess,
onError,
options);
on code trn hot ng, ta phi chc chn l to ra cc phn t DOM tng ng thch
hp nh sau :
<div id=my_x></div>
<div id=my_y></div>
<div id=my_z></div>
<div id=my_timestamp></div>
watchID);
navigator.accelerometer.clearWatch(
39
<!DOCTYPE html>
<html>
<head>
<title>Acceleration Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
var watchID = null;
// Wait for PhoneGap to load
document.addEventListener(deviceready, onDeviceReady, false);
// PhoneGap is ready, start watching
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
function startWatch() {
// Update acceleration every 3 seconds
var options = { frequency: 3000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError,
options);
}
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
40
}
// onError: Failed to get the acceleration
//
function onError() {
alert(oooops!);
}
</script>
</head>
<body>
<div id=accelerometer>Waiting for accelerometer...</div>
<button onclick=stopWatch();>Stop Watching</button>
</body>
</html>
41
IV.V tr a l Geolocation
4.1.Th no l v tr a l Geolocation ?
Geolocation bao hm cch xc nh v tr a l tht ca 1 thit b - trong trng hp ny l
in thoi smartphone m ta s dng.cch thng thng nht xc nh v tr a l ca 1
thit b l s dng tnh nng GPS cha bn trong smartphone dng xc nh kinh v
v
Tuy nhin, 1 vi thit b c th s dng nhng dch v khc suy lun ra 1 v tr v d
nh : 1 a ch IP, xc nh tn s radio (RFID), a ch truy cp wifi (MAC), hay trm pht
sng.bi v c rt nhiu phng thc khc nhau c s dng thu thp cc ta v tr,
do vy khng ai c th m bo rng phonegap API s tr v v tr tht s ca thit b
42
43
44
Position
PositionError
Coordinates
V d gi hm geolocation.getCurrentPosition() nh v d di th kt qu tr v gm c
kinh , v , cao, chnh xc, chnh xc cao, tiu , tc , v timestamp,
c truyn vo hm onSuccess :
alert(Latitude: + position.coords.latitude + \n +
Longitude: + position.coords.longitude + \n +
Altitude: + position.coords.altitude + \n +
Accuracy: + position.coords.accuracy + \n +
Altitude Accuracy: + position.coords.altitudeAccuracy + \n +
Heading: + position.coords.heading + \n +
Speed: + position.coords.speed + \n +
Timestamp: + new Date(position.timestamp) + \n);
}
function onError(error) {
alert(code: + error.code + \n +
message: + error.message + \n);
}
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
45
PositionError.PERMISSION_DENIED
PositionError.POSITION_UNAVAILABLE
PositionError.TIMEOUT
Tc speed l tc so vi mt t (m/s)
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
46
Cch v d hot ng
Khi ng dng c ti xong th phng thc watchPosition() c kch hot v c mi 3
giy th thit b li nhn c 1 cp nht mi v kinh v v
47
tin hnh giao din UI, u tin ta phi chc chn rng project ca ta c cc th mc
jQTouch cn thit bn trong n nh c m t trong chng trc.lu t ln u
on code sau on script ti phonegap.js:
<style type=text/css media=screen>@import jqtouch/jqtouch.css;</style>
<style type=text/css media=screen>@import themes/jqt/theme.css;</style>
<script src=jqtouch/jquery-1.4.2.js type=text/javascript charset=utf-8></script>
<script src=jqtouch/jqtouch.js type=application/x-javascript charset=utf-8></script>
<script type=text/javascript charset=utf-8>
var jQT = new $.jQTouch({
icon: jqtouch.png,
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
48
49
50
51
V.Media
5.1.Cc Media Files l g ?
Media API cho php ta ghi li v chi cc file m thanh audio trn 1 thit b.c bit l ta c
th chy cc files audio c load trc tip trn thit b hay chi cc files audio ti v thng
qua internet
52
Tt nhin, ch v apple cung cp nhng app ny min ph th khng c ngha l nhng app
khc ging nh vy khng tn ti.hnh 9-2 ch ra rng c v s cc app nh vy trn app
store.v tt c chng cung cp cng nhng tnh nng c bn nh nhau - record, pause,
play, v stop recording.1 vi c thm kh nng chia s cc file ghi m qua e-mail, cc dch
v chia s media
53
1 la chn ph bin l Pandora nh hnh 9-4, ng dng ny hng ti dch v music trn
web.v dch v Pandora a ra 1 cch th v ti cng 1 bn nhc.iu ny c ngha l khi
ta mun nghe music ca nhm nhc Creedence Clearwater Revival (CCR).th ta to ra 1
trm station dnh cho ban nhc ny v sau Pandora s tm kim m nhc ch khng
ch chn la cc bn ghi m ca CCR m cn tm kim cc bi ht khc t cc ban nhc
khc cng th loi nhc m ta mun tm.sau ta c th chia s trm radio station mi
ny cho nhng ngi khc
54
cc tham s ch c :
55
Android
iOS
V d mu :
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
setInterval(function,mi
llisec,lang)hm ny
// Update media position every second
c tc dng gi lp i
lp li 1 hm function
no theo 1 chu k
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum 56
thi gian millisec
position) {
function(
if (
console.log((
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
}
);
}, 1000);
5.5.2.Phng thc media.getDuration
media.getDuration();
Phng thc getDuration() l 1 hm khng ng b (ngha l n khng t gi li lin tc
theo chu k m mun nh vy ta phi thit lp bng tay) dng tr v khong thi gian ca
audio file c tnh theo giy nu bit.cn nu khong thi gian l cha xc nh th n
tr v gi tr l -1
Phng thc ny h tr cc nn tng :
Android
iOS
57
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Get duration
var counter = 0;
var timerDur = setInterval(function() {
counter = counter + 100;
clearInterval(id_of_setinterval)
xa b i s lp li ca hm
function c lp bi
setInterval vi
var id_of_setinterval =
setInterval(function,milisec)
Android
iOS
58
} ;
// Play audio
my_media.play();
setTimeout(code,millisec,lang)
hm hn gi gi hm
(khng thc hin lp li theo
chu k)
59
// Play audio
my_media.play();
}
Ch :
Trong BlackBerry WebWorks :
Trong iOS :
numberOfLoops
60
Android
iOS
V d mu :
61
// error callback
function(err) {
console.log("recordAudio():Audio Error: "+ err.code);
});
// Record audio
mediaRec.startRecord();
}
62
Ch :
Trong BlackBerry WebWorks :
Cc thit b blackberry ghi li audio trong nhiu nh dng c cht lng khc
nhau.cc file ny phi kt thc vi ui m rng l .amr
Trong iOS :
Android
iOS
V d mu :
/ Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
63
// Play audio
my_media.play();
Android
iOS
V d mu :
// Record audio
//
function recordAudio() {
var src = "myrecording.mp3";
var mediaRec = new Media(src,
// success callback
function() {
console.log("recordAudio():Audio Success");
},
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
64
// error callback
function(err) {
console.log("recordAudio():Audio Error: "+ err.code);
});
// Record audio
mediaRec.startRecord();
MediaError.MEDIA_ERR_ABORTED
MediaError.MEDIA_ERR_NETWORK
MediaError.MEDIA_ERR_DECODE
MediaError.MEDIA_ERR_NONE_SUPPORTED
Cch tip cn thn thin cho vn kim sot li ny l thit lp 1 mng array cha cc
trng thi li s dng cc constants ging nh l cc ch mc key, v tng ng vi n l
cc thng bo li t nh ngha.theo cch ny ta c th hin th nhng thng bo li d hiu
ti ngi dng nh sau :
funciton onError(error){
var errors = {};
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
65
66
67
68
69
ci thin giao din ngi dng, u tin ta phi m bo rng project ca ta cn thit
phi c cc th mc jQTouch folders trong n, nh ni n trong cc chng
trc.t on code ny vo trc on load phonegap.js:
<style type=text/css media=screen>@import jqtouch/jqtouch.css;</style>
<style type=text/css media=screen>@import themes/jqt/theme.css;</style>
<script src=jqtouch/jquery-1.4.2.js type=text/javascript charset=utf-8></script>
<script src=jqtouch/jqtouch.js type=application/x-javascript charset=utf-8></script>
<script type=text/javascript charset=utf-8>
var jQT = new $.jQTouch({
icon: jqtouch.png,
icon4: jqtouch4.png,
addGlossToIcon: false,
startupScreen: jqt_startup.png,
70
71
72
VI.Lu tr Storage
Ta ang l nh pht trin HTML5, th hu nh ta chy ng dng trong cc thit lp cu hnh
nm pha client.
V d : nu ta s dng trnh duyt Chrome or Safari v vo trang
html5demos.com/database, th ta s nhn thy trang page ny c lm y bi cc dng
tweets.nhn thong qua th ta cm tng trang page ny xut hin bi c h tr bi 1
database nh thng l ging kiu MySQL.tuy nhin khi ta n chut phi vo trang page
n vo Inspect Element.ta s thy nh trong hnh 11-1
73
74
75
window.localStorage.key(0) // kt qu l Lp
window.localStorage.key(1) // kt qu l ho v tn
window.localStorage.key(2) // kt qu l sinh ngy
76
window.localStorage.clear();
Database openDatabase(
in DOMString name,
in DOMString version,
in DOMString displayName,
in unsigned long estimatedSize,
in optional DatabaseCallback creationCallback
);
Tham s:
-
name: tn ca database.
version: phin bn. (Hai database trng tn nhng khc phin bn th khc nhau)
displayname: m t.
creationCallback: phng thc callback c thc thi sau khi database m/to.
77
78
interface SQLTransaction {
void executeSql(in DOMString sqlStatement, in optional ObjectArray arguments, in
optional SQLStatementCallback callback, in optional SQLStatementErrorCallback
errorCallback);
};
[Callback=FunctionOnly, NoInterfaceObject]
interface SQLStatementCallback {
void handleEvent(in SQLTransaction transaction, in SQLResultSet resultSet);
};
[Callback=FunctionOnly, NoInterfaceObject]
interface SQLStatementErrorCallback {
boolean handleEvent(in SQLTransaction transaction, in SQLError error);
};
79
80
?,?)", [1,"peter"]);
81
?,?)", [2,"paul"]);
82
tx) {
myDB.transaction(
function
populateDB(tx) {
83
6.4.Cch xem 1 tp kt qu
1 trong nhng th ta thng lm nhiu hn thng thng, l ta s lm vi database l lu
tr v cch nhn gi tr t n.
Phng thc giao dch transaction cung cp cho ta 1 hm success callback.phng thc
executeSql() cng cung cp cho ta cc hm success v error callbacks.trong hm
success callback ta s nhn thy tp kt qu.
Nu ta s dng v lm vic vi mySQL (hay 1 vi SQL database khc), th ta c th ngh
mi vic cn lm u ging nh vy. Nhng g m ta ly li t hm success callback l 1
i tng SQLResultSet object l i tng cha 3 thuc tnh sau :
rows;
};
SQLResultSetRowList :
interface SQLResultSetRowList {
readonly attribute unsigned long length;
84
Nh thy trn
function
queryDB(tx) {
}
Theo nh ngha v SQLTransaction trn
SELECT * FROM test l tham s bt buc
function querySuccess(tx, results) {
alert(Insert ID = + results.insertId);
function
errorDB(err) {
tm lm ti thng tin kt qu tr v, do vy ta
db.transaction(
queryDB, errorDB);
85
function querySuccess(tx,
results) {
results.rows.length;
{
alert(Row = + i + Firstname = +
Lastname = +
results.rows.item(i).firstname +
results.rows.item(i).lastname);
Vi firstname v lastname l
tn 2 ct trong database
}
}
V d trc s dng 1 vng lp for lp thng qua cc tp bng ghi.vng lp for l 1 khi
to tt y bi v ta khng bit c bao nhiu ln, ta phi lp thng qua 1 tp bn ghi, bi v
m tp bn ghi c 1 chiu di khc nhau, ph thuc vo cu truy vn v d liu c lu
tr
lp thng qua 1 tp bn ghi, ta phi bit di ca tp bn ghi ny (do ta s dng
results.rows.length ).khi ta c n, ta c th bt u bn ghi u tin c nhn v, v
x l tng dng bng cch s dng results.row.item(i).field_name , ti y field_name
tng ng vi tn 1 trng field trong database
6.5.iu chnh li
Nu c 1 li xy ra, th phonegap s vng ra 1 i tng SQLError object, n cha 2 thuc
tnh sau :
86
SQLError.UNKNOWN_ERR
SQLError.DATABASE_ERR
SQLError.VERSION_ERR
SQLError.TOO_LARGE_ERR
SQLError.QUOTA_ERR
SQLError.SYNTAX_ERR
SQLError.CONSTRAINT_ERR
SQLError.TIMEOUT_ERR
87
Constant
Code
Situation
UNKNOWN_ERR
DATABASE_ERR
VERSION_ERR
TOO_LARGE_ERR 3
88
SYNTAX_ERR
CONSTRAINT_ER
<!DOCTYPE html>
<html>
<head>
<title>Database Example</title>
<script type=text/javascript charset=utf-8 src=phonegap.js></script>
<script type=text/javascript charset=utf-8>
document.addEventListener(deviceready, onDeviceReady, false);
function populateDB(tx) {
tx.executeSql(DROP TABLE IF EXISTS test1);
tx.executeSql(CREATE TABLE IF NOT EXISTS test1 (id unique, name));
tx.executeSql(INSERT INTO test1 (id, name) VALUES (1, Tony));
tx.executeSql(INSERT INTO test1 (id, name) VALUES (2, Bill));
tx.executeSql(INSERT INTO test1 (id, name) VALUES (3, Thomas));
}
function queryDB(tx) {
tx.executeSql(SELECT * FROM test1, [], querySuccess, errorCB);
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
89
90
VII.Files
7.1.H thng FILESYSTEMS
Bt chp nh sn xut hay h iu hnh, mi smartphone hay thit b cn phi c 1 h
thng filesystem v Phonegap API cung cp cho ta 1 vi cch truy cp ti h thng
filesystem ny
Vo thi im hin ti, kh nng truy cp ny cn kh nhiu hn ch.v d, rt kh (hay c
l l khng th ) nhy ra ngoi hp ct sandbox m ng dng b cha bn trong.tuy
nhin, ta gi nh rng ta khng y hc v cch b kha in thoi ( v d nh b
kha cho in thoi c kh nng h tr b nh ln ti 16 GB )
Nhng g chng ny tp trung l cch truy cp vo h thng filesystem v vy m ta c
th c 1 file v ghi 1 vi d liu vo file
i tng PhoneGaps FileSystem object miu t thng tin v h thng filesystem, v n c
2 thuc tnh sau :
Android
iOS
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
onSuccess,
onFail);
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
91
function
onSuccess(fileSystem){
alert(fileSystem.
name);
alert(fileSystem.
root.name);
}
function
onFail(event){
target.error.code);
alert(event.
}
Thuc tnh
92
nn tng h tr :
Android
iOS
7.2.2.getMetadata
phng thc s dng tm kim thng tin metadata v 1 th mc dn directory.n c 2
tham s l 2 hm callback :
93
y l 1 v d :
function onSuccess(metadata) {
alert(Last Modified: + metadata.modificationTime);
}
function onFail(error) {
alert(error.code);
}
// Request the metadata object for this entry
entry.getMetadata(onSuccess, onFail);
7.2.3.setMetadata
phng thc thit lp thng tin metadata trn 1 th mc dn directory, hin ti ch hot
ng trn iOS
cc tham s truyn vo :
v d nh :
function success() {
console.log("The metadata was successfully set.");
}
function fail() {
alert("There was an error in setting the metadata");
}
{ "com.apple.MobileBackup": 1});
94
{key : value}
Phonegap cho ngi mi hc
7.2.4.moveTo
phng thc ny c s dng chuyn 1 th mc dn directory ti 1 v tr khc trn h
thng filesystem.s xy ra li khi ta c thc hin cc thao tc sau :
V d :
function success(entry) {
alert(New Path: + entry.fullPath);
}
function fail(error) {
alert(error.code);
}
function moveDirectory(entry) {
95
var
parent = document.getElementById(parent).value,
newName = document.getElementById(newName).value,
entry.moveTo(
}
7.2.5.copyTo
phng thc ny c s dng sao chp 1 th mc dn ti 1 v tr khc trn h thng
filesystem.bt k thao tc no sau y cng gy ra li :
Ch : sao chp th mc lun lun l qui v s s thc hin sao chp ton b
ni dung c trong th mc
cc tham s cho phng thc ny :
V d :
function success(entry) {
alert(New Path: + entry.fullPath);
}
function fail(error) {
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
96
parent = document.getElementById(parent).value,
newName = document.getElementById(newName).value,
entry.copyTo(
}
7.2.6.toURI
phng thc ny dng tr v 1 URL m c th dng xc nh v tr 1 th mc dn
v d :
// Get the URI for this directory
var uri = entry.toURI();
alert(uri);
7.2.7.remove
phng thc ny dng xa 1 th mc dn.v th mc dn ny phi trng rng
1 trong cc thao tc sau s gy li :
nu ta c th xa 1 th mc dn m n khng rng
v d :
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
97
7.2.8.getParent
phng thc ny c s dng tm kim th mc dn cha m ang cha th mc dn
hin ti.phng thc ny gm 2 tham s :
v d :
function success(parent) {
alert(Parent: + parent.name);
}
function fail(error) {
alert(Failed to get parent: + error.code);
}
// Get the parent DirectoryEntry
entry.getParent(success, fail);
7.2.9.createReader
phng ny c s dng to ra 1 i tng DirectoryReader mi m c th c cc
thc th t 1 th mc dn
v d :
// create a directory reader
var directoryReader = entry.createReader();
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
98
7.2.10.getDirectory
phng ny c s dng to ra hay tm kim 1 th mc dn.s c li xy ra nu ta c
gng thc hin :
v d :
function success(parent) {
alert(Parent: + parent.name);
}
function fail(error) {
alert(Unable to create new directory: + error.code);
}
// Retrieve an existing directory, or create it if it does not already exist
entry.getDirectory(sampleFiles, {create: true, exclusive: false}, success, fail);
7.2.11.getFile
phng thc ny c s dng to ra hay tm kim 1 file .nu ta c gng to ra 1 file m
th mc cha ca n cha tn ti th s gy ra li
cc tham s dnh cho phng thc ny :
99
v d :
function success(parent) {
alert(Parent: + parent.name);
}
function fail(error) {
alert(Failed to retrieve file: + error.code);
}
// Retrieve an existing file, or create it if it does not exist
entry.getFile(sample_data.txt, {create: true, exclusive: false}, success, fail);
7.2.12.removeRecursively
phng thc ny c s dng xa 1 th mc dn v tt c phn t cha trong
n.trong trng hp li v d nh ta c xa 1 th mc dn m c cha 1 file khng th b
xa th 1 vi ni dung ca th mc dn c th b xa.nu ta c gng xa th mc gc root
ca filesystem th cng s gy ra li
cc tham s dnh cho phng thc ny :
v d :
function success(parent) {
alert(Delete succeeded!);
}
function fail(error) {
alert(Failed tod elete directory or its contents: + error.code);
}
// remove the directory and all its contents
100
7.3.metadata
i tng ny cung cp thng tin v trng thi ca 1 file hay ca 1 th mc dn
thuc tnh :
Android
iOS
V d :
function win(
metadata) {
metadata.modificationTime);
101
7.4.FileError
1 i tng FileError c thit lp khi 1 li xy ra trong bt c phng thc File API no
Cc thuc tnh :
Cc hng s :
FileError.NOT_FOUND_ERR
FileError.SECURITY_ERR
FileError.ABORT_ERR
FileError.NOT_READABLE_ERR
FileError.ENCODING_ERR
FileError.NO_MODIFICATION_ALLOWED_ERR
FileError.INVALID_STATE_ERR
FileError.SYNTAX_ERR
FileError.INVALID_MODIFICATION_ERR
FileError.QUOTA_EXCEEDED_ERR
FileError.TYPE_MISMATCH_ERR
FileError.PATH_EXISTS_ERR
Thng tin m t :
i tng FileError object ch l 1 tham s duy nht trong bt k hm File API's error
callbacks no.cc nh pht trin phi c thuc tnh code xc nh dng li
7.5.Flags
i tng ny c s dng cung cp cc tham s cho phng thc getFile v
getDirectory ca i tng DirectoryEntry cc phng thc ny dng tm kim hay
to ra cc files v th mc 1 cch tng ng
Cc thuc tnh :
102
Cc nn tng h tr :
Android
iOS
V d :
// Get the data directory, creating it if it doesn't exist.
dataDir = fileSystem.root.getDirectory("data",
{create: true});
7.6.LocalFileSystem
i tng ny cho bit 1 cch ly v th mc gc root ca file systems
Cc phng thc :
cc hng s :
103
Cc nn tng h tr :
Android
iOS
V d :
function onSuccess(fileSystem) {
console.log(fileSystem.name);
}
7.7.DirectoryReader
1 i tng m lit k cc files v cc th mc dn trong 1 th mc
Cc phng thc :
cc nn tng h tr :
Android
iOS
104
v d :
function success(
entries) {
var i;
for (i=0; i<
entries.length; i++) {
console.log(
entries[i].name);
}
}
function fail(error) {
alert("Failed to list directory contents: " + error.code);
}
cc phng thc :
105
remove xa 1 file
cc nn tng h tr :
Android
iOS
7.8.1.getMetadata
y l phng thc c s dng tm kim metadata v 1 file.nh rng metadata ca
file nm tch bit vi data tht s ca n v metadata c th l cc thng tin v thi im
to file, kch thc ca file hay hn th
cc tham s ca phng thc ny chnh l 2 hm callback :
errorCallback 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object.
V d :
function success(metadata) {
alert(Last Modified: + metadata.modificationTime);
}
function fail(error) {
alert(error.code);
}
// Request the metadata object for this entry
entry.getMetadata(success, fail);
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
106
7.8.2.moveTo
phng thc ny c s dng chuyn 1 file ti 1 v tr khc trn h thng filesystem.s
xy ra li khi ta c thc hin cc thao tc sau :
cc tham s :
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(entry) {
alert(New Path: + entry.fullPath);
}
function fail(error) {
alert(error.code);
}
function moveFile(entry) {
var parent = document.getElementById(parent).value,
parentEntry = new DirectoryEntry({fullPath: parent});
// move the file to a new directory and rename it
entry.moveTo(parentEntry, new_file.txt, success, fail);
}
107
7.8.3.copyTo
sao chp 1 file ti 1 v tr khc trn h thng filesystem .s xy ra li khi ta c thc hin cc
thao tc sau :
cc tham s :
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(entry) {
alert(New Path: + entry.fullPath);
}
function fail(error) {
alert(error.code);
}
function copyFile(entry) {
var parent = document.getElementById(parent).value,
parentEntry = new DirectoryEntry({fullPath: parent});
// copy the file to a new directory and rename it
entry.copyTo(parentEntry, file.copy.txt, success, fail);
}
108
7.8.4.toURI
tr v 1 URL m c th c s dng xc nh v tr 1 file
v d :
// Request the metadata object for this entry
var uri = entry.toURI();
console.log(uri);
7.8.5.remove
phng thc ny c s dng xa 1 file
cc tham s l 2 hm callback :
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(entry) {
alert(Removal succeeded);
}
function fail(error) {
alert(Error removing file: + error.code);
}
// remove the file
entry.remove(success, fail);
7.8.6.getParent
tm kim th mc cha DirectoryEntry ang cha file
cc tham s :
109
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(parent) {
console.log("Parent Name: " + parent.name);
}
function fail(error) {
alert(error.code);
}
7.8.7.createWriter
ta c th vit 1 file vo 1 th mc dn bng cch s dng phng thc createWriter.n to
ra 1 i tng FileWriter object c lin kt vi file ny
cc tham s :
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(writer) {
writer.write("Some text to the file");
}
function fail(error) {
alert(error.code);
}
110
7.8.8.file
tr v 1 i tng File object dng miu t trng thi hin ti ca file
cc tham s :
errorCallback - 1 hm callback c gi nu c 1 li xy ra , n c gi vi i
tng FileError object. (Function)
v d :
function success(file) {
console.log("File size: " + file.size);
}
function fail(error) {
alert("Unable to retrieve file properties: " + error.code);
}
111
cc phng thc :
Android
iOS
7.9.1.readAsDataURL
ta c th c 1 file v tr v d liu nh l d liu c m ha Base64-encoded, phng
thc ny thng dng c cc nh images v cc files nh phn khc.
Tham s truyn vo l file l i tng file object c
V d :
file) {
function win(
console.log("read success");
console.log(evt.target.result);
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
112
};
file);
reader.readAsDataURL(
};
entry.file(win, fail);
7.9.2.abort
ta c th dng vic c 1 file bng cch s dng phng thc abort nh v d sau :
file) {
function success(
file);
reader.readAsText(
reader.abort();
}
function fail(error) {
console.log(error.code);
}
entry.file(success, fail);
113
7.9.3.readAsText
cc tham s :
114
115
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
onprogress c trong khi vn thc hin ghi file, bo co li tin trnh thc hin
(progess.loaded/progress.total). (Function)
116
Cc nn tng h tr:
Android
iOS
V d:
Seek
function win(writer) {
// fast forwards file pointer to end of file
writer.seek(writer.length);
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
Truncate
function win(writer) {
writer.truncate(10);
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
Write
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
117
Append
function win(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.seek(writer.length);
writer.write("appended text");
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
Abort
function win(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write("some sample text");
writer.abort();
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
118
119
</script>
</head>
<body>
<h1>Example</h1>
<p>Write File</p>
</body>
</html>
Android
iOS
7.11.1.upload
var ft = new FileTransfer();
ft.upload(fileURI, serverURL, onUploadSuccess, onUploadError,
fileUploadOptions);
vi :
120
121
122
123
7.11.2.download
var ft = new FileTransfer();
ft.download(source, target, successCallback, errorCallback);
vi :
124
7.11.3.abort
Dng hy b 1 tin trnh truyn dn file ang c thc hin. hm onerror callback s
c gi vi 1 tham s truyn vo l i tng FileTransferError object
Cc nn tng h tr:
Android
iOS
7.11.4.onprogress
c gi vi 1 s kin ProgressEvent bt c khi no 1 khc d liu mi c truyn i.
Cc nn tng h tr:
Android
iOS
125
7.12.FileTransferError
1 i tng FileTransferError object c tr v thng ua 1 hm error callback khi c 1 li
xy ra trong tin trnh ti ln hay ti xung 1 file
Cc thuc tnh:
http_status m trng thi HTTP status code. Thuc tnh ny s ch xut hin khi 1
m phn hi c nhn v t kt ni HTTP connection. (Number)
cc hng s:
FileTransferError.FILE_NOT_FOUND_ERR
FileTransferError.INVALID_URL_ERR
FileTransferError.CONNECTION_ERR
FileTransferError.ABORT_ERR
126
VIII.Camera
PhoneGap Camera API cung cp cho 1 ng dng kh nng lm vic vi cc images hay
kh nng chp nh t camera hay nhn file nh t kho nh trong thit b.khi ly v 1 nh
image th API c th tr v 1 URL ch ti image file trn thit b hay chui base64-encoded
string dng biu din ni dung bn trong 1 image
API cung cp 1 phng thc n l navigator.camera.getPicture dng ly v 1 nh
image v 1 i tng cameraOptions object c s dng nh ngha cc tham s
xung quanh vic nh image c nhn v nh th no, cch n c nh dng nh th
no ,
Cc ng dng Apps cng c th s dng PhoneGap Capture API chp nh bng cch
s dng camera. Camera v Capture APIs l khc nhau do vy n s nh hng ti
nh gi ca ta trc khi la chn ci no l cn thit cho ng dng
127
{});
}
function onCameraSuccess(imageURL)
navigator.notification.alert("onCameraSuccess: " +
imageURL);
}
function onCameraError(e) {
navigator.notification.alert("onCameraError: " + e);
}
</script>
</head>
<body onload="onBodyLoad()">
<h1>Example 11-1</h1>
<p>Using the PhoneGap Camera API<br />
<input type="button" value="Take a Picture"
onclick="takePhoto();">
</p>
</body>
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
128
129
130
Ch trn hnh l khng c cch no hy b tin trnh x l.nu ngi dng khi to 1
tin trnh chp nh trong ng dng phonegap ang chy trn IOS th khng c cch no
hy b tin trnh ny m khng phi chp 1 bc hnh
Trn thit b IOS, sau khi chp xong hnh th ng dng s hin th ra 1 thng bo hin th
ra file URI cho image file va mi c to ra nh hnh 11-3
131
132
133
134
135
136
{quality : 50,
}
destinationType : Camera.DestinationType.FILE_URI );
}
function onCameraSuccess(
imageURL) {
137
imageURL +
138
139
quality
destinationType
sourceType
allowEdit
encodingType
targetWidth
targetHeight
mediaType
mi mt thuc tnh cu hnh trn s c m t chi tit hn trong phn ngay sau
y.ging vi nhiu tnh nng khc ca PhoneGap APIs th cc cu hnh ca API no (
ging nh allowEdit trong Camera API ) ch p dng c trn gii hn 1 s cc nn tng
mobile
y l 1 v d mu v 1 i tng cameraOptions object y m ta c th s dng :
var cameraOptions = { quality : 75,
sourceType : Camera.PictureSourceType.CAMERA,
destinationType : Camera.DestinationType.FILE_URI,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 1024,
targetHeight: 768 };
khi chuyn tip vo hm getPicture function,th i tng cameraOptions object ny ni
cho getPicture, phng thc ny ly nh v t camera (sourceType), v tr v file URI
dng ch ti image file c chp (destinationType), cho php ngi dng chnh
sa li bc hnh trc khi tr n v chng trnh (allowEdit), tr v 1 nh dng .jpeg file
(encodingType), thit lp image file c m ha s dng 75% cht lng nh
(quality) v thit lp phn gii ca nh l 1024 by 768 pixels (targetWidth v
targetHeight).
8.2.1.Quality
Khi lm vic vi smartphone cameras th phn gii quang hc cao trong thu knh
camera s cng dn, thm vo b nh lu tr gii hn v bng thng truyn dn trn thit
b, do vy cn thit phi c cch nn cc nh images ny chng chim t b nh lu tr
hn v gim ti bng thng truyn dn.ging nh l 1 phn ca tin trnh nn ny , cc tiu
chun nh nh ngha JPEG c h tr bng cch s dng cht lng nh kim sot
Ng Quang Trung email: ngotrung.poli.t@gmail.com / www.phonegap.vn/forum
140
8.2.2.destinationType
khi chp 1 bc hnh bng cch s dng getPicture th ng dng s s dng
destinationType iu khin kiu d liu no v image, s c tr v ging nh 1 file
URI dng ch ti image file c lu tr trong b nh ca thit b :
destinationType: Camera.DestinationType.FILE_URI
Hay ly v d liu nh theo gi tr kiu chui base64-encoded string th ta s dng nh
sau :
141
142
8.2.3.sourceType
tham s sourceType c s dng nh ngha ni m phng thc getPicture ly nh
v.khi sourceType b b qua th phng thc getPicture s n gin s dng
Camera.SourceType.CAMERA ly nh v.ng dng c th nh ngha s dng th vin
nh trong thit b bng cch sau :
sourceType : Camera.SourceType.PHOTOLIBRARY
ly v cc nh t 1 album nh lu, bng cch s dng sau :
sourceType : Camera.SourceType.SAVEDPHOTOALBUM
trn hu ht cc nn tng, cch nh ngha sourceType l SAVEDPHOTOALBUM hay
PHOTOLIBRARY thc cht l ging nhau.nh hnh 11-9, khi ng dng to ra 1 li gi
getPicture th thit b s m ng dng th vin nh v cho php ngi dng u tin l la
chn 1 album nh v sau la chn 1 bc nh trc khi tr v 1 nh c chn ti
ng dng Phonegap
143
Ch : Camera.PictureSourceType.PHOTOLIBRARY v
Camera.PictureSourceType.SAVEDPHOTOALBUM c tnh nng ging ht nhau trong
Android v cu hnh sourceType khng c h tr trong BlackBerry
144
8.2.4.allowEdit
1 ng dng IOS c th s dng cu hnh allowEdit ch dn phng thc getPicture cho
php ngi dng chnh sa nh c chn, trc khi tr v cho ng dng Phonegap.
thit lp 1 i tng cameraOptions object cho cu hnh ny ta s dng nh sau :
allowEdit : true
khi c kch hot trong ng dng th sau khi camera chp nh th thit b s hin th 1 mn
hnh tng t vi hnh 11-10.ti y, ngi dng c th chnh sa li bc nh.khi ngi
dng n vo nt Choose button th nh c chnh sa s c tr v cho ng dng
PhoneGap
145
8.2.7.mediaType
trong nhiu smartphones hin i ngy nay, chng c th cha nhiu loi media types
trong 1 photo library th PhoneGap Camera API h tr b sung 1 gi tr mediaType trong
cameraOptions object trong trng hp m sourceType thit lp l PHOTOLIBRARY
hay SAVEDPHOTOALBUM.tham s ny h tr cc cu hnh sau :
146
8.2.8.saveToPhotoAlbum
dng lu nh vo photo album trn thit b sau khi chp xong
saveToPhotoAlbum : true
147
Khi ng dng chy trn thit b m khng c camera th ta s nhn thy li ging nh hnh
11-12 sau :
148
149
150
IX.Splashscreen
Cho php lp trnh vin hin th hay n i mn hnh splash screen ca ng dng
Cc phng thc:
Show
Hide
iOS
Cordova.plist
Add an entry under the Plugins dictionary - with the key "SplashScreen" and value
"CDVSplashScreen".
New projects should already have this key.
10.2.Cch thit lp
Android:
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 10000);
151
10.3.show
Hin th mn hnh splash screen.
navigator.splashscreen.show();
cc nn tng h tr:
Android
iOS
152
10.4.hide
n i mn hnh splash screen.
navigator.splashscreen.hide();
cc nn tng h tr:
Android
iOS
153
Ch : 1 vi mo cho iOS:
1. trong Cordova.plist, ta cn hiu chnh gi tr "AutoHideSplashScreen thnh false
2. sau , nu ta mun n i mn hnh splash screen khong 2 giy, th ta c th lm
nh sau trong hm hiu chnh event deviceready
setTimeout(function() {
navigator.splashscreen.hide();
}, 2000);
154
155