You are on page 1of 107

Li ni u

ng trc xu th ton cu ho, ngnh dch v Vin thng ni chung v dch v in thoi di ng ni ring Vit Nam t c nhng thnh tu nht nh. S khai l mt ngnh vi nhng iu kin c s vt cht ngho nn, dch v vin thng cn rt lc hu. Cho n nay, ngnh Vin thng Vit nam ho nhp vi mng thng tin ton cu, ng gp vo GDP 0,2% nm 1991 v n nay ln ti con s 10,5%. c bit s lng thu bao dch v in thoi di ng thay i mt cch nhanh chng, t 4.060 thu bao nm 1993 ln ti 1.200.000 thu bao tnh n ht thng 3 nm 2005. Trc xu th hi nhp ngy cng m rng, ngnh dch v Vin thng ni chung v dch v in thoi di ng ni chung ang bc vo giai on cnh tranh rt ln. Ni ln trong giao on hin nay l cng ngh h iu hnh di ng v ni bt nh mt ngi sao mi l h iu hnh Android ca Google.

Chng I: Tm hiu v Android

I.1 Android l g? Android l mt phn mm stack cho cc thit b di ng bao gm mt h iu hnh, middleware v cc ng dng quan trng. Android SDK cung cp cc cng c v API cn thit bt u pht trin cc ng dng trn nn tng Android bng cch s dng ngn ng lp trnh Java. I.2 Nhng c tnh ng dng framework cho php ti s dng v thay th cc thnh phn Dalvik my o c ti u ha cho cc thit b di ng Tch hp trnh duyt da trn ng c WebKit m ngun m

Ti u ha ha c h tr bi mt ty chnh ha 2D th vin; ha 3D da trn nhng c im k thut OpenGL ES 1,0 (Ty chn tng tc phn cng ) SQLite cho vic lu tr d liu cu trc Phng tin truyn thng h tr cho m thanh ph bin, video, v vn cn nh dng hnh nh (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)

GSM in thoi (ph thuc phn cng) Bluetooth, EDGE, 3G v WiFi (ph thuc phn cng ) Camera, GPS, la bn, v gia tc (ph thuc phn cng)

Mi trng pht trin phong ph bao gm mt m phng thit b, cng c g li, b nh v profiling hiu sut, v mt plugin cho IDE Eclipse

I.3 Kin trc Android


S di y cho thy cc thnh phn chnh ca h iu hnh Android. Mi phn c m t chi tit hn di y.

I.3.1 ng dng Android s ship vi mt b cc ng dng li bao gm mt ng dng email, lch chng trnh tin nhn SMS,, bn , trnh duyt, lin lc, v nhng ngi khc. Tt c cc ng dng c vit bng cch s dng ngn ng lp trnh Java. I.3.2 ng dng Framework Bng cch cung cp mt nn tng pht trin m, Android cung cp cho cc nh pht trin kh nng xy dng cc ng dng v cng phong ph v sng to. Cc nh pht trin c min ph tn dng li th ca cc thit b phn cng, thng tin a im truy cp, dch v chy nn, thit lp h thng bo ng, thm cc thng bo n cc thanh trng thi, v nhiu, nhiu hn na. Cc nh pht trin c th truy cp vo cc API cng mt khun kh c s dng bi cc ng dng li. Kin trc ng dng c thit k n gin ha vic ti s dng cc thnh phn; bt k ng dng c th xut bn cc kh nng ca mnh v ng dng no khc sau c th lm cho vic s dng nhng kh nng (ty thuc vo ch bo m thi hnh theo khun kh). C ch ny cng cho php cc thnh

phn c thay th bi ngi s dng. Nm bn di tt c cc ng dng l mt tp hp cc dch v v h thng, bao gm: Mt tp phong ph v m rng ca xem c th c s dng xy dng mt ng dng, bao gm cc danh sch, li, hp vn bn, cc nt, v thm ch mt trnh duyt web nhng Nh cung cp ni dung cho php cc ng dng truy cp d liu t cc ng dng khc (nh Contacts), hoc chia s d liu ca ring mnh

Mt qun l ti nguyn, cung cp quyn truy cp vo ti nguyn phi m nh dy bn a ho, ha, v b tr tp tin.

Mt Notification Manager cho php tt c cc ng dng ty chnh hin th cnh bo trong thanh trng thi.

Mt Activity Manager qun l vng i ca cc ng dng v cung cp mt backstack ph bin chuyn hng.

I.3.3 Th vin Android bao gm mt b th vin C/C++, c s dng bi cc thnh phn khc nhau ca h thng Android. Nhng kh nng tip xc vi cc nh pht trin thng qua cc khun kh ng dng Android. Mt s cc th vin li c lit k di y:

System C library - mt BSD-c ngun gc thc hin cc h thng th vin chun C (LIBC), iu chnh cho nhng da trn Linux cc thit b Media Libraries - da trn OpenCORE PacketVideo's; s h tr cc th vin pht li v ghi m ca m thanh v ph bin nhiu nh dng video, cng nh cc tp tin hnh nh tnh, bao gm MPEG4, H.264, MP3, AAC, AMR, JPG, v PNG Surface Manager - qun l quyn truy cp vo h thng con hin th v hon ton ph hp cht 2D v 3D lp t nhiu ng dng ha LibWebCore - mt trnh duyt web hin i, ng c c quyn hn c hai trnh duyt web ca Android v mt xem nhng SGL - cc cng c ha 2D tim n 3D libraries - mt vic thc hin da trn OpenGL ES 1,0 API; cc th vin, hoc s dng phn cng tng tc 3D (nu c) hoc bao gm, cao ti u rasterizer phn mm 3D SQLite - mt mnh m v nh quan h c s d liu c sn cho tt c cc ng dng

I.3.4 Thi gian chy Android Android bao gm mt tp cc th vin li m cung cp hu ht cc chc nng sn c trong th vin ct li ca ngn ng lp trnh Java. Mi ng dng Android chy trong tin trnh ring ca mnh, vi trng hp ring ca cc my o Dalvik. Dalvik c vit nn mt thit b c th chy nhiu my o hiu qu. VM Dalvik thc hin tc phm trong cc Executable Dalvik (dex). nh dng c ti u ha cho b nh ti thiu. VM l ng k trn, v chy cc lp hc bin son bi mt trnh bin dch ngn ng Java c chuyn thnh cc nh dng dex. Do dx "bao gm" cng c. VM Dalvik da vo ht nhn Linux cho cc chc nng tim n nh lung v cp qun l b nh thp.

Chng II: S dng ti nguyn trong ng dng Android


Bn nn lun lun s dng ngun ti nguyn nh hnh nh v chui t m ng dng ca bn, bn c th duy tr chng mt cch c lp. Externalizing ngun lc ca bn cng cho php bn ti cung cp ngun ti nguyn thay th c h tr cu hnh thit b c th nh ngn ng khc nhau hoc kch c mn hnh, m ngy cng tr nn quan trng nh nhiu thit b h tr Android tr nn c sn vi cc cu hnh khc nhau. cung cp kh nng tng thch vi cu hnh khc nhau, bn phi t chc cc ngun lc trong th mc res d n ca bn, bng cch s dng sub th mc khc nhau, nhm cc ti nguyn theo loi hnh v cu hnh. i vi bt c loi ti nguyn, bn c th mc nh v thay th nhiu ngun lc cho ng dng ca bn: Mc nh l nhng ti nguyn c s dng khng ph thuc vo cu hnh thit b hoc khi khng c ngun ti nguyn thay th ph hp vi cu hnh hin ti.

Thay th cc ngun lc c cc mc bn thit k s dng vi mt cu hnh c th. xc nh n mt nhm cc ngun lc cho mt cu hnh c bit, thm mt vng loi cu hnh ph hp vi tn th mc.

V d, trong khi mc nh layout giao din ca bn c lu trong th mc res/layout/, bn c th xc nh mt layout giao din khc nhau c s dng khi mn hnh nh hng phong cnh, bng cch lu n trong th mc res/layout-

land/. Android s t ng p dng cc ngun lc thch hp bng cch kt hp cu hnh hin ti ca thit b ti tn th mc ti nguyn ca bn.

(nh minh ha t http://developer.android.com/images/resources/resource_devices_diagram1.png) Hnh 1 th hin nh th no mt tp hp cc ngun ti nguyn mc nh t mt ng dng c p dng cho hai thit b khc nhau khi khng c ngun ti nguyn thay th c sn.

(nh minh ha t http://developer.android.com/images/resources/resource_devices_diagram2.png) Hnh 2 cho thy vic p dng cng vi mt tp hp cc ngun ti nguyn thay th n iu kin i vi mt trong cc cu hnh thit b, do , hai thit b s dng ngun ti nguyn khc nhau. Thng tin trn ch l gii thiu v cch lm vic ngun lc ng dng trn Android. Cc ti liu sau y cung cp mt hng dn y ti lm th no bn c th t chc cc ngun lc ng dng ca bn, xc nh ngun ti nguyn thay th, truy cp chng trong ng dng ca bn, v nhiu hn na: Vic cung cp ti nguyn : Nhng loi ti nguyn m bn c th cung cp trong ng dng ca bn, ni ti lu li, v lm th no to ra ngun lc thay th cho cc cu hnh thit b c th. Truy cp cc ti nguyn : Lm th no ti s dng cc ngun lc m bn cung cp, hoc bng cch tham chiu n chng t m ng dng ca bn hoc t cc ngun khc XML. X l Thay i Runtime : Lm th no ti qun l thay i cu hnh xy ra trong khi Activity ca bn ang chy.

Localization : Met hng dn t di ln ti a phng ha n ca bn bng cch s dng ngun ti nguyn thay th. Trong khi y ch l mt c th s dng ti nguyn thay th, n l rt quan trng tip cn ngi dng hn. Cc loi ti nguyn : Mt ti liu tham kho ca cc loi ti nguyn khc nhau, bn c th cung cp, m t XML ca h yu t, thuc tnh, v c php. V d, tham chiu ny cho thy bn lm th no to ra mt ngun lc cho cc menu ng dng, drawables, hnh ng, v nhiu hn na. Cc loi ti nguyn trong ng dng Android Mi ca cc ti liu trong phn ny m t vic s dng, nh dng v c php cho mt loi ti nguyn ng dng m bn c th cung cp trong th mc ti nguyn ca bn (res/). Di y l tm tt ca tng loi ti nguyn:

Ti nguyn hnh nh ng : Xc nh hnh nh ng c xc nh trc.


Tween hnh nh ng c lu trong res/Anim/ v truy cp t cc lp R.anim. Frame hnh nh ng c lu trong res/drawable/ v truy cp t cc lp R.drawable.

Danh sch State ti nguyn mu : Xc nh mt ti nguyn mu sc n thay i da trn cc tiu bang View.

Lu trong res/color v truy cp t cc lp R.color. Lu trong res/drawable/ v truy cp t cc lp R.drawable.

Ti nguyn Drawable : Xc nh ha khc nhau vi bitmap hoc XML.

B tr ngun lc : Xc nh layout cho giao din ngi dng ng dng ca bn.


Lu trong res/layout/v truy cp t cc lp R.layout. Lu trong res/menu/ v truy cp t cc lp R.menu.

Menu Resource : Xc nh ni dung ca cc menu ng dng ca bn. Ti nguyn String : Xc nh cc chui, mng chui, v s nhiu (v bao gm cc nh dng chui v to kiu tc).

Lu trong res/value/ v truy cp t cc lp R.string, R.array, v R.plurals.

Ti nguyn phong cch : Xc nh xem xt v nh dng cho cccc yu t giao din ngi dng .

Lu trong res/value/ v truy cp t cc lp R.style.

Cc loi ti nguyn khc : Xc nh gi tr nh cc php ton lun, s nguyn, kch thc, mu sc, v cc mng khc.

Lu trong res/value/ nhng mi truy cp t duy nht R tiu hc (nh R.bool, R.integer, R.dimen, vv.) Qun l vng i ca mt Service trong Android

Vng i ca mt service n gin hn nhiu so vi cc activity. Tuy nhin, n thm ch cn quan trng hn, bn c phi quan tm ti cch service ca bn c to ra v hy dit, bi v mt service c th chy trong background m khng cho ngi dng c bit. Vng i ca mt Service, t khi n c to ra cho khi n b ph hy, c th theo hai con ng khc nhau:

Mt service started : Cc service c to ra khi component khc gi startService(). Cc service sau n chy v thi hn v dng li bng cch gi stopSelf(). Mt component khc cng c th dng dch v bng cch gi stopService(). Khi dch v ny c dng li, h thng tiu dit n .. Mt service bound : Cc service c to ra khi mt component (mt client) gi bindService(). Client sau giao tip vi cc service thng qua mt giao din IBinder. Cc client c th ng kt ni bng cch gi unbindService(). Nhiu khch hng c th lin kt vi cc service tng t v khi tt c chng unbind, h thng s ph hy cc service. (chnh n khng cn dng li.)

Hai con ng khng hon ton ring bit. Bn c th lin kt vi mt dch v c started vi startService(). V d, mt service background m nhc c th c started bng cch gi startService() vi mt nh nhn dng m nhc

chi. Sau , c th khi ngi dng mun thc hin mt s kim sot i vi cc cu th hoc nhn c thng tin v cc bi ht hin hnh, mt activity c th lin kt vi cc service bng cch gi bindService(). Trong trng hp nh th ny, stopService() hoc stopSelf() khng thc s dng service cho n khi khch hng unbind tt c . Trin khai thc hin vng i callback Ging nh mt activity, mt service c vng i method callback v bn c th trin khai theo di nhng thay i trong trng thi ca service v thc hin cng vic vo thi im thch hp. Cc service th hin skeleton sau mi vng i ca cc method:

(nh minh ha c s dng t http://developer.android.com/images/service_lifecycle.png) Hnh 2. Cc vng i service. S bn tri cho thy vng i khi dch v c to ra vi startService() v s bn phi cho thy vng i khi dch v c to ra vi bindService(). Bng cch thc hin nhng phng php ny, bn c c th theo di hai vng lp lng nhau trong vng i ca service:

S sng ca mt service xy ra gia thi gian onCreate() c gi v onDestroy() thi gian tr v. Ging nh mt activity, mt service khng thit lp ban u trong onCreate() cho n v tt c cc ngun lc cn li trong onDestroy(). V d, mt service nghe nhc c th to ra cc ch

m m nhc s c chi trong onCreate(), sau dng thread trong onDestroy(). Cc onCreate() v onDestroy() method c gi cho tt c cc dch v, cho d h ang to ra bi startService() hoc bindService().

Cc cuc i hot ng ca mt service bt u vi mt cuc gi n hoc l onStartCommand() hoc onBind(). Mi phng php c a cc nh c thng qua hoc l startService() hoc bindService(), tng ng.

Nu service c started, cc hot ng kt thc cuc i cng thi im kt thc ton b cuc i (dch v ny vn cn hot ng ngay c sau khi onStartCommand() tr v). Nu dch v c bound, kt thc cuc i hot ng tr li khi onUnbind(). Tm hiu v Activity trong Android Activity Mt l mt thnh phn ng dng cung cp mt mn hnh m ngi dng c th tng tc lm mt ci g , chng hn nh quay s in thoi, chp nh, gi email, hoc xem mt bn . Mi activity c cho mt ca s, trong cho v giao din ngi dng ca n. Ca s thng lp y mn hnh, nhng c th nh hn so vi mn hnh v ni ln trn cc ca s khc. Mt ng dng thng bao gm nhiu activity c rng buc lng lo vi nhau. Thng thng, mt trong nhng activity trong mt ng dng c quy nh nh cc activity "chnh", c trnh by cho ngi dng khi tung ra ng dng cho ln u tin. Mi activity sau c th bt u activity khc thc hin hnh ng khc nhau. Mi ln mt activity mi bt u, cc activity trc c dng li, nhng h thng cc khu bo v cc activity trong mt ngn xp (cc "back stack"). Khi mt activity mi bt u, n c y ln pha sau ngn xp v vic ch trng ca ngi dng. S tr li ngn xp tun th cc c bn "last in, first out" c ch hng i, do , khi ngi dng c thc thi vi cc activity hin ti v nhn phm BACK, n l popped khi ng (v ph hy) cc h s activity trc . (S tr li ngn xp c tho lun nhiu hn trong cng vic v sp xp li ti liu.) to ra mt activity, bn phi to mt sub class ca Activity. Trong sub class ca bn, bn cn cho thc thi method gi h thng cc cuc gi khi chuyn i activity gia cc state khc nhau cho vng i ca n, chng hn nh khi activity ang c to ra, dng li, ni li, hoc b ph hy. Hai phng php gi li quan trng nht l:

Create Activity Bn phi trin khai method ny. H thng cc cuc gi ny khi to activity ca bn. Trong thi hn trin khai thc hin ca bn, bn nn khi to cc thnh phn thit yu ca activity ca bn. Quan trng nht, y l ni bn phi gi setContentView() xc nh vic layout cho giao din ngi dng ca activity. Start Activity Khi lm vic trong ng dng ca ring bn, bn thng s cn cho n gin l khi ng mt activity c bit n. Bn c th lm nh vy bng cch to ra mt intent r rng xc nh activity bn mun bt u, s dng tn lp. V d, y l cch mt activity bt u activity khc c tn SignInActivity: Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); ng mt Activity Bn c th ng mt activity bng cch gi methos finish() ca n. Bn cng c th ng ca mt activity ring bit trc bn bt u bng cch gi finishActivity(). Ngoi ra trong Activity cn nhiu method khc,

Qun l vng i Activity Qun l vng i Activity ca bn bng cch thc hin gi method l rt quan trng cho pht trin mt ng dng mnh m v linh hot. Vng i ca mt activity trc tip b nh hng bi kt hp nhim v ca n v back stack vi cc activity khc. Mt hot ng c th tn ti trong ba trng thi c bn: Resumed, Paused v Stopped Nu mt activity b tm dng hoc dng li, h thng c th drop n t b nh hoc l bng cch yu cu cho n kt thc (gi method finish() ca n), hoc n gin l git cht qu trnh ca n. Khi hot ng ny c m li (sau khi c finished hoc cht), n phi c to ra nh trn. Tm hiu v Service trong Android Service l mt ng dng component c th thc hin cc hot ng long-running trong background v khng cung cp mt giao din ngi dng. Mt ng dng component c th bt u mt service v n s tip tc chy trong background

thm ch nu ngi dng chuyn cho ng dng khc. Ngoi ra, mt component c th lin kt cho mt dch v tng tc vi n v thm ch thc hin giao tip InterProcess (IPC). V d, mt dch v c th x l cc giao dch mng, nghe nhc, thc hin cc tp tin I/O, hoc tng tc vi mt provider content, tt c t background. Mt service c bn c th c hai hnh thc: Started service l "started" khi mt component ng dng (nh mt activity) bt u n bng cch gi startService (). Khi bt u, mt service c th chy trn background v thi hn, ngay c khi cc thnh phn bt u n b ph hy. Thng thng, mt service bt u thc hin mt hot ng n l v khng tr li kt qu cho ngi gi. V d, n c th ti v hoc ti ln mt tp tin qua mng. Khi hot ng c thc hin, cc service nn dng li bn thn. Bound service l "bound" khi mt component ng dng lin kt cho n bng cch gi bindService (). Mt service rng buc cung cp mt giao din client-server cho php cc component tng tc vi cc dch v, gi cc yu cu, c c kt qu, v thm ch lm nh vy qua qu trnh giao tip InterProcess (IPC). Mt service bound ch chy min l ng dng component khc b rng buc vo n. Nhiu thnh phn c th lin kt cho dch v cng mt lc, nhng khi tt c chng unbind, service ny b ph hy. Cc khi nim c bn : to ra mt service, bn phi to mt lp dch v (hoc mt trong cc subclasses hin ti ca n). Trong implementation ca bn, bn cn cho ghi ln mt s method gi li c th x l cc kha cnh quan trng ca vng i service v cung cp mt c ch cho cc component cho gn kt vi dch v, nu thch hp. Cc method quan trng nht bn c nn ghi ln gi l:

onStartCommand() H thng gi method ny khi component nh l mt activity, yu cu cc service c started, bng cch gi startService (). Sau khi thc hin phng php ny, cc service c khi ng v c th chy trong background v thi hn. Nu bn c trin khai iu ny, l trch nhim ca bn dng dch v khi cng vic ca mnh c thc hin, bi stopSelf gi in thoi () hoc stopService (). (Nu bn c ch mun cung cp rng buc, bn khng cn phi trin khai method ny.) onBind() H thng gi method ny khi component mun lin kt vi cc service (chng hn nh cho thc hin RPC), bng cch gi bindService(). Trong implementation ca bn ca phng php ny, bn c phi cung cp mt giao din khch hng s dng giao tip vi dch v, bng cch tr li mt IBinder. Bn lun lun phi

trin khai phng php ny, nhng nu bn khng mun cho php lin kt, sau bn nn tr v null. onCreate() H thng gi method ny khi service u tin to ra, thc hin cc th tc thit lp mt ln (trc khi cuc gi hoc l onStartCommand() hoc onBind()). Nu service ang chy, phng php ny khng c gi. onDestroy() H thng gi method ny khi service khng cn c s dng v ang c b ph hy. service ca bn nn trin khai iu ny cho lm sch bt c ngun ti nguyn nh ch , ngi nghe ng k, nhn, vv y l cc cuc gi qua dch v ny nhn c. Giao din ngi dng trong Android Trong mt ng dng Android, giao din ngi dng c xy dng bng cch s dng View v ViewGroup i tng. C nhiu loi quan im v cc nhm view, mi mt trong s l hu du ca lp View. View objects l cc n v c bn ca biu hin giao din ngi dng trn nn tng Android. Cc class xem nh l c s phc v cho class con c gi l "widget", trong cung cp y cc i tng thc hin giao din, ging nh cc lnh vc vn bn v nt. Class ViewGroup phc v nh l c s cho lp con c gi l " layouts", cung cp cc loi khc nhau ca kin trc b tr, nh linear, tabular v relative. Mt View object l mt cu trc d liu c c tnh lu tr cc thng s b tr v ni dung cho mt khu vc c th hnh ch nht ca mn hnh.

Mt View object x l o lng ring ca mnh, b tr, bn v thay i tp trung,, di chuyn, v phm/tng tc c ch cho khu vc hnh ch nht ca mn hnh.

L mt object trong giao din ngi dng, view cng l mt im tng tc cho ngi s dng v nhn cc s kin tng tc. Xem Hierarchy Trn nn tng Android, bn xc nh mt hot ng ca giao din ngi dng bng cch s dng mt h thng phn cp ca View v ViewGroup, nh trong biu di y.

Cy ny c th c phn cp n gin hay phc tp nh bn cn n c, v bn c th xy dng n ln bng cch s dng thit lp Android ca widgets v layouts nh sn, hoc vi Views ty chnh m bn to ra cho mnh. nh km vi cy phn cp xem mn hnh cho rendering, Hot ng ca bn phi gi setContentView() Phng php v thng qua mt tham chiu n i tng button gc. H thng Android nhn c tp tin ny v s dng n lm mt hiu lc, o lng, v v cy. Nt gc ca cc yu cu phn cp cho n v cc nt con - ln lt, mi nt view l nhm chu trch nhim ku gi mi ln view nt con ring ca mnh v c th yu cu mt kch thc v v tr trong nt gc., Nhng i tng viewgroup c quyt nh cui cng v ni lm th no, c th c cho mi nt con. Android parses cc yu t ca cch b tr ca bn trong th t (t pha trn cng ca cy phn cp), instantiating vic xem v thm chng vo parent(s). Bi v y l nhng trch ra trong trt t, nu c cc yu t chng cho nhau cc v tr, mt ln cui c rt ra s nm trn u trang ca nhng ngi khc trc y rt ra khng gian . Giao din Cch ph bin nht xc nh b tr ca bn v th hin s phn cp view l vi mt tp tin XML layout. XML cung cp mt c cu c th c c cho b tr, ging nh HTML. Mi phn t trong XML l c mt View hoc i tng ViewGroup (hoc hu du ). Cc i tng View l l trong cy, ViewGroup i tng l cc nhnh trong cy. Tn ca mt phn t XML l tng ng vi lp hc Java m n i din. V vy, mt yu t <textview> to ra mt TextView trong UI ca bn, v mt phn t

<linearlayout> to ra mt LinearLayout viewgroup. Khi bn ti mt layout resource, h thng Android khi chy thi gian cc i tng, tng ng vi cc yu t trong cch b tr ca bn. V d, mt b tr dc n gin vi mt ln xem vn bn v mt nt s nh th ny:

<? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> Ch rng cc phn t LinearLayout cha c TextView v Button. Bn c th lm khc LinearLayout (hoc cc loi hnh xem nhm) bn trong y, ko di s phn cp xem v to ra mt b cc phc tp hn. bit thm v vic xy dng mt b cc UI, c Giao din k khai. C rt nhiu cch m bn c th xem cch b tr ca bn. S dng nhiu hn v cc loi khc nhau ca cc view group, bn c th cu trc views con v view groups trong v s cch . Xc nh cc nhm xem c cung cp bi Android (gi l layouts) bao gm LinearLayout, RelativeLayout, TableLayout, GridLayout v khc. Mi cung cp mt b duy nht ca cc thng s b tr c s dng xc nh v tr ca views con v c cu layout tm hiu v mt s cc loi khc nhau ca cc view group c s dng cho mt layout, c Giao din i tng thng gp. Widgets Widget l mt object View phc v nh mt giao din tng tc vi ngi dng. Android cung cp mt tp cc widgets thc hin y , ging nh cc button, Checkbox, v text-entry , do bn c th nhanh chng xy dng giao din ngi dng ca bn. Mt s widgets c cung cp bi Android phc tp hn, ging nh mt date picker, clock, v zoom controls. Nhng n khng gii

hn trong cc loi widgets c cung cp bi cc nn tng Android. Nu bn mun lm mt ci g thm cho ty bin v to ra cc yu t ca hnh ng ca bn, bn c th, bng cch xc nh object view ca ring bn hoc bng cch m rng v kt hp cc Widget hin c. c tip ti Building Custom Components. c mt danh sch cc vt dng c cung cp bi Android, xem gi android.widget UI S kin Mt khi bn thm mt s Views/widgets n giao din, c th bn mun bit v s tng tc ca ngi dng vi h, v vy bn c th thc hin hnh ng. c thng bo v UI events ngi dng, bn cn phi lm mt trong hai iu:

Xc nh mt s kin nghe v ng k n vi cc View. Khc thng hn khng, y l cch bn s lng nghe cho cc s kin. Cc class View c cha mt tp hp cc giao din lng nhau t tn On<something>Listener, u c mt phng php gi li c gi l On<something>() V d. View.OnClickListener ( x l "nhp chut" trn mt View), View.OnTouchListener ( x l cc s kin mn hnh cm ng trong mt View), v View.OnKeyListener ( x l thit b p quan trng trong mt View). V vy nu bn mun View ca bn c thng bo khi n l " clicked" (chng hn nh khi mt nt c chn), thc hin v xc nh OnClickListener ca n gi method onClick() (ni bn thc hin cc hnh ng sau khi nhp chut), v ng k n vo Xem vi setOnClickListener() Ghi mt callback method hin cho View. y l nhng g bn nn lm g khi bn thc hin lp View ca ring bn v mun lng nghe cho cc s kin c th xy ra trong n. V d v cc s kin bn c th x l bao gm mn hnh l touched onTouchEvent() khi trackball l di chuyn onTrackballEvent() hoc khi mt phm trn thit b c nhn onKeyDown(). iu ny cho php bn xc nh cc hnh vi mc nh cho tng s kin bn trong tu chnh View ca bn v xc nh xem s kin ny cn c thng qua ngy View con khc. Mt ln na, y l nhng callbacks View class, do , c hi duy nht ca bn xc nh l khi bn xy dng mt phn ty chnh.

Menus Menu n c mt phn quan trng ca giao din ngi dng trong mt ng dng. Menus cung cp mt giao din ng tin cy cho thy rng cc chc nng ng dng v ci t. Trong trnh n ng dng ph bin nht l tit l bng cch bm phm MENU trn thit b. Tuy nhin, bn cng c th thm Context Menus, c th hin

th khi ngi s dng my nhn v nm gi phm trn mt mc. Thc n cng c h thng phn cp cu trc bng cch s dng mt xem, nhng bn khng xc nh cu trc ny cho mnh. Thay vo , bn xc nh onCreateOptionsMenu() hoc onCreateContextMenu() gi method cho hot ng ca bn v tuyn b cc mc m bn mun bao gm trong menu ca bn. Trong mt thi gian thch hp, Android s t ng to ra h thng View phn cp cn thit cho menu, v rt ra mi trong mi menu items . Menus cng x l cc s kin ring ca n, do khng cn phi ng k s kin listeners trn cc item trong menu ca bn. Khi mt item trong menu ca bn c chn, onOptionsItemSelected() hoc onOptionsItemSelected() onContextItemSelected() method onContextItemSelected() s c gi bng framework. V cng ging nh layout ca bn, bn c ty chn khai bo cc menu item cho bn trong mt tp tin XML. c To Menus tm hiu thm. Adapters Thnh thong bn s mun populate mt view group vi mt s thng tin m khng th hard-coded c, thay vo , bn mun bind xem mt ngun d liu bn ngoi. lm iu ny, bn s dng mt AdapterView xem nh l view group ca bn v View con c khi to v populated vi d liu t Adapter. Cc i tng AdapterView l mt implementation ca ViewGroup xc nh nhng view con ca n da trn mt i tng Adapter nht nh. Adapter cc hnh vi nh l chuyn pht nhanh gia cc ngun d liu ca bn (c l l mt mng ca chui bn ngoi) v AdapterView, hin th n trong . C mt s hin thc ca class Adapter, cho nhim v c th, chng hn nh CursorAdapter vic c d liu c s d liu t mt Cursor, hoc mt ArrayAdapter c t mt mng ty . tm hiu thm v cch s dng mt adapter cho populate views ca bn, hy c ng vo d liu vi AdapterView. Styles and Themes C l bn khng hi lng vi dng v ca cc widgets tiu chun. sa i chng, bn c th to mt s style ring v ch ca bn.

Mt Style l mt tp hp ca mt hay nhiu thuc tnh nh dng m bn c th p dng nh mt n v n cc yu t c nhn trong layout ca bn. V d, bn c th xc nh mt Style ch nh mt vn bn kch thc v mu sc nht nh, sau p dng n ch cc yu t View c th. Mt Theme l mt tp hp ca mt hay nhiu thuc tnh nh dng m bn c th p dng nh mt n v n tt c cc hot ng trong mt ng

dng, hoc ch hot ng n l. V d, bn c th nh ngha mt theme m b mu sc c th cho khung ca s v nn bng, v t kch c ch v mu sc cho cc menu. Theme ny sau c th c p dng cho cc hot ng c th hoc ng dng ton b. Styles and themes l ngun ti nguyn. Android cung cp mt s kiu mc nh v style and themes m bn c th s dng, hoc bn c th pht trin ring ti nguyn style and theme ca bn. Learn more about using styles and themes in the Applying Styles and Themes document. Tm hiu thm v cch s dng phong cch v ch trong cc ng dng Styles v ti liu . K thut x l b nh trong Android Mobile Android ng dng, trn T-Mobile G1, c gii hn t nht 16 MB ca heap. l b nh cho in thoi v rt t cho nhng g mt s nh pht trin mun t c. Thm ch nu bn khng k hoch s dng tt c cc b nh ny, bn nn s dng t nht c th cho cc ng dng khc chy m khng phi o thi chng. Cc ng dng khc Android c th gi trong b nh, nhanh hn, cho ngi s dng chuyn i gia cc ng dng ca mnh. L mt phn ca cng vic ca ti, ti chy vo cc vn r r b nh trong cc ng dng Android v chng ti thy c phn ln thi gian do cc sai lm: gi qu lu cho tham chiu n mt Context. Trn Android, mt Context c s dng cho nhiu hot ng, nhng ch yu l ti v truy cp ti nguyn. y l l do ti sao tt c cc widgets nhn c mt s Context trong xy dng ca h. Trong mt ng dng bnh thng ca Android, bn thng c hai loi Context Activity v Application. N thng l mt trong nhng ci u tin m nh pht trin i n cc classes v methods cn mt Context : @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); setContentView(label); } iu ny c ngha l Views c mt tham chiu n ton b hot ng v do bt c iu g n Activity ang nm gi; thng c View ton b h thng phn cp v tt c cc ngun ti nguyn ca n. V vy, nu bn b r r cc Context ( "leak" c ngha l nh vy bn gi mt tham chiu n n, ngn chn cc GC t

thu thp), bn b r r rt nhiu b nh. R r ton b hot ng c th thc s d dng nu bn khng cn thn. Khi nh hng s thay i h thng, theo mc nh, tiu hu activity hin ti v to ra mt ci mi trong khi gi trng thi. Trong khi lm iu , Android s ti li giao din ca ng dng t cc ngun ti nguyn. By gi hy tng tng bn vit mt ng dng vi mt bitmap ln m bn khng mun thay phin tt c. Cch n gin nht gi cho n xung quanh v khng phi ti xoay vng li mi ngy nn n trong static field: private static Drawable sBackground; @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); } M ny l rt nhanh v cng rt sai, n to ra leak cc hot ng u tin khi thay i nh hng. Khi mt Drawable c nh km View, view c thit lp nh l mt callback trn drawable. Trong on m trn, iu ny c ngha l drawable c mt tham chiu n TextView m t n c mt tham chiu n cc hot ng (trong Context m ln lt c tham chiu kh nhiu n bt c iu g (ty thuc vo m ca bn.) V d ny l mt trong nhng trng hp n gin nht leaking ca cc Context v bn c th xem th no, chng ti lm vic xung quanh n trong m ngun ca cc mn hnh ch (tm unbindDrawables() method) bng cch thit lp cc callbacks drawables lu tr null khi Activity ny ph hy. iu th v, c nhng trng hp bn c th to ra mt chui cc hon cnh b r r, v kh khn. N lm cho bn ht b nh kh nhanh chng. C hai cch d dng trnh r r b nh ng cnh c lin quan. The most obvious one is to avoid escaping the context outside of its own scope. Mt r rng nht l trnh bi cnh bn ngoi phm vi ca chnh mnh.

V d trn cho thy trng hp ca mt tham chiu tnh nhng bn trong classe v tim n reference cho class bn ngoi c th nguy him nh nhau. The second solution is to use the Application context. Gii php th hai l s dng ng cnh Application. Context ny s khng sao min l ng dng ca bn vn hot ng v khng ph thuc vo chu k hot ng ca activities. Nu bn c k hoch duy tr lu di sng cc i tng m cn mt bi cnh , nh i tng p dng. Bn c th c c n mt cch d dng bng cch gi Context.getApplicationContext() hoc Activity.getApplication() Tm li, trnh nhng context c lin quan r r b nh, xin hy nh:

Khng gi tham chiu n context activity qu lu(mt tham chiu n mt activity nn c chu k sng tng t nh cc hot ng chnh n) Trnh non-static bn trong cc classes ca mt activity nu bn khng kim sot vng i ca n, s dng mt class static bn trong v thc hin mt tham chiu yu n activity bn trong. Cc gii php cho vn ny l s dng mt static class bn trong vi mt WeakReference cho class bn ngoi, nh thc hin trong ViewRoot v lp ca n chng hn Khai bo Layout trong Android

Hy th s dng cc context ca application thay v context ca activity

Mt b thu rc khng phi l mt bo him chng r r b nh. Layout ca bn l kin trc cho cc giao din ngi dng trong mt Activity. N xc nh c cu v nm gi cc yu t xut hin cho ngi dng thy. Bn c th khai bo layout ca bn theo hai cch:

Khai bo phn t UI trong XML. Android cung cp mt vn t vng n gin XML tng ng vi cc lp View v subclasses, chng hn nh widget v layout. Khi to cc yu t layout trong thi gian chy. ng dng ca bn th to ra i tng View v ViewGroup (v thao tc cc properties ca n) theo chng trnh.

Vit XML S dng vn t vng ca Android XML, bn c h nhanh chng thit k UI layout v cc thnh phn cha chng, ging nh cch bn to cc trang web trong HTML - vi mt lot cc phn t lng nhau. Mi tp tin layout phi bao gm phn t gc mt cch chnh xc, v phi l mt i tng View hoc ViewGroup. Mt khi bn xc nh cc phn t gc, bn c th thm i tng layout b sung hoc cc widget nh l cc phn t con cho

tng bc xy dng mt h thng View nh ngha layout ca bn. V d, y l c layout XML c s dng mt LinearLayout dc cho t chc mt TextView v mt Button: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> Sau khi bn khai bo layout ca bn trong XML, lu tp tin vi phn m rng .xml, trong th mc res/layout/ d n Android ca bn, do , ng cch bin dch. Np ti nguyn XML Khi bn bin dch ng dng ca bn, mi tp tin XML layout l bin dch vo mt ngun ti nguyn View. Bn cn phi ti cc ngun ti nguyn layout t m ng dng ca bn, trong Activity.onCreate() callback implementation ca bn. Lm nh vy bng cch gi setContentView(), qua n tham chiu cho ti nguyn layout ca bn trong cc hnh thc: R.layout.layout_file_name V d : nu XML layout ca bn c lu nh main_layout.xml, bn s ti n cho Activity ca bn nh sau: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } Thuc tnh ca Layout khai bo trong Android

Mi i tng View v ViewGroup h tr a dng ca ring n cc thuc tnh XML. Mt s thuc tnh c c th cho mt i tng View (v d, TextView h tr thuc tnh textSize), nhng cc thuc tnh ny cng c k tha bi bt c i tng View c th m rng lp ny. Mt s c s dng chung cho tt c i tng View, bi v n c tha k t lp View gc(ging nh cc thuc tnh id). V, cc thuc tnh khc c coi l "tham s layout", m c thuc tnh m t nh hng layout nht nh ca i tng View, theo nh ngha ca i tng l i tng ViewGroup parent. ID Bt k i tng View c th c ID s nguyn lin kt vi n, nhn din ra cc View bn trong cy. Khi ng dng bin dch, ID ny l tham chiu nh l mt s nguyn, nhng ID thng c giao trong layout cc file XML nh mt chui, trong thuc tnh id. y l thuc tnh chung cho tt c i tng View (c nh ngha bi lp View) v bn s s dng n rt thng xuyn. C php ca c ID, bn trong th XML l: android:id="@+id/my_button" Ti biu tng (@) ti u ca chui cho thy rng c php XML cn phn tch v m rng phn cn li ca chui ID v xc nh n nh l mt ngun ti nguyn ID. Cc biu tng cng (+) c ngha rng y l mt tn ti nguyn mi phi c to ra v thm ngun ti nguyn ca chng ti (trong file R.java). C mt s ti nguyn ID khc c cung cp bi cc khun kh Android. android:id="@android:id/empty" to ra views v tham kho chng t ng dng, mt m hnh ph bin l: Xc nh group/widget trong tp tin layout v gn cho n mt m s duy nht: <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/>

Sau to mt instance ca i tng group v nm bt n t layout (thng thng dng trong method onCreate()): Button myButton = (Button) findViewById(R.id.my_button);

Xc nh ID cho cc i tng group l quan trng khi to ra mt RelativeLayout. Trong cch b tr tng i, views sibling c th xc nh layout ca mnh tng i khc group sibling, l tham chiu bi ID duy nht.

Mt ID khng cn phi l duy nht trong sut ton b cy, nhng n cn l duy nht trong mt phn ca cy bn ang tm kim (thng c th l ton b cy, v vy tt nht cho l hon ton c nht khi c th). Layout Parameters layout cc thuc tnh c tn l XML nh ngha cc thng s layout_something layout cho cc View thch hp cho cc ViewGroup trong c tr. Mi lp ViewGroup thc hin m rng mt lp ViewGroup.LayoutParams lng nhau. Lp ny c cha cc loi properties xc nh kch thc v v tr cho tng group child, nh thch hp cho nhm group. Nh bn nhn thy hnh 1, cc nhm parent group thng s xc nh layout cho tng group con(bao gm c nhm group child).

(nh minh ha c s dng t http://developer.android.com/images/layoutparams.png) Lu tt c cc lp con LayoutParams c c php ca ring mnh thit lp cc gi tr. Mi phn t child phi xc nh LayoutParams thch hp cho parent ca n, mc d n cng c th nh ngha LayoutParams khc nhau cho con ca n. Tt c cc view group bao gm chiu rng v chiu cao (layout_width v layout_height), v mi group bt buc nh ngha cho n. Rt nhiu LayoutParams cng bao gm margins v borders. K thut s dng phin bn API c v mi trn Android Mobile Mt lot cc thit b Android c h tr ang sn c cho ngi tiu dng trn th gii. Trn cc thit b, mt lot cc phin bn nn tng Android ang s dng, mt s chy phin bn mi nht, nhng ngi khc ang chy phin bn c. L mt nh pht trin, bn cn phi xem xt cc cch tip cn tng thch trong ng dng

ca bn - bn c mun cho php cc ng dng ca bn chy trn tt c cc thit b, hoc ch nhng ngi ang chy phn mm mi nht? Trong mt s trng hp, n s hu ch s dng cc API mi hn trn cc thit b c h tr n, trong khi tip tc h tr thit b c. t minSdkVersion Nu vic s dng mt API mi c tch ri vo ng dng - c l bn cn ghi li bng cch s dng mt API c gii thiu trong Android 1,5 (API Level 3) bn nn thm mt <android:minSdkVersion> n ng dng, m bo ng dng ca bn s khng c ci t trn cc thit b c. V d, nu ng dng ca bn ph thuc vo mt API c gii thiu trong API Level 3, bn s ch nh "3" l gi tr ca cc phin bn SDK ti thiu: <manifest> ... ... <uses-sdk android:minSdkVersion="3" /> ... ... </manifest> Tuy nhin, nu bn mun thm mt tnh nng hu ch nhng khng cn thit, chng hn nh popping lp mt bn phm trn mn hnh ngay c khi c mt bn phm phn cng c sn, bn c th vit chng trnh ca bn mt cch cho php n s dng cc tnh nng mi hn m khng tht bi trn thit b c. S dng reflection Gi s c mt simple mi gi bn mun s dng, nh android.os.Debug.dumpHprofData(String filename). Cc lp debug tn ti t Android 1.0, nhng l phng php mi trong Anroid 1.5 (API Level 3). Nu bn c gng gi n trc tip, ng dng ca bn s khng chy trn cc thit b chy Android 1.0 hoc sm hn. Cch n gin gi method l thng qua reflection. iu ny i hi phi thc hin mt thi gian tra cu v kt qu l b nh m trong mt i tng Method. S dng phng php l mt vn ca gi Method.invoke v kt qu un-boxing. Xem xt sau y: public class Reflect { private static Method mDebug_dumpHprofData; static { initCompatibility(); };

private static void initCompatibility() { try { mDebug_dumpHprofData = Debug.class.getMethod( "dumpHprofData", new Class[] { String.class } ); /* success, this is a newer device */ } catch (NoSuchMethodException nsme) { /* failure, must be older device */ } } private static void dumpHprofData(String fileName) throws IOException { try { mDebug_dumpHprofData.invoke(null, fileName); } catch (InvocationTargetException ite) { /* unpack original exception when possible */ Throwable cause = ite.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { /* unexpected checked exception; wrap and re-throw */ throw new RuntimeException(ite); } } catch (IllegalAccessException ie) { System.err.println("unexpected " + ie); } } public void fiddle() { if (mDebug_dumpHprofData != null) { /* feature is supported */ try { dumpHprofData("/sdcard/dump.hprof"); } catch (IOException ie) { System.err.println("dump failed!"); } } else { /* feature not supported, do something else */

System.out.println("dump not supported"); } } } M ny s dng mt initializer tnh gi initCompatibility m khng tra cu cc phng php. Nu iu thnh cng, n s dng mt phng php ring vi ng ngha ging nh (lp lun ban u, gi tr tr v, kim tra trng hp ngoi l) thc hin cuc gi. Gi tr tr li (nu n c mt) v trng hp ngoi l c m gi v tr li mt cch bt chc bn gc. Cc phng php fiddle minh chng cch logic ng dng s chn gi API mi hoc lm iu g khc nhau da trn s hin din ca phng php mi. i vi mi phng php b sung m bn mun gi, bn s thm mt private Method field, initializer field, v wrapper gi class. Cch tip cn ny tr nn phc tp hn mt cht khi phng php ny l declared trong mt undefined class trc y. N cng chm hn gi Method.invoke() hn l gi phng thc trc tip. Nhng vn ny c th c gim nh bng cch s dng mt lp wrapper. S dng mt lp wrapper tng l to ra mt class kt thc tt p m tt c cc API mi tip xc bi mt class mi hay class hin c. Mi phng thc trong lp wrapper ch cc cuc gi thng qua method thc t tng ng v tr v kt qu tng t. Nu target class v method tn ti, bn s c c nhng hnh vi v bn s nhn c bng cch gi cc class trc tip, vi mt lng nh trn khng t cuc gi phng thc b sung. Nu target class hoc method khng tn ti, vic khi to ca class wrapper tht bi, v ng dng ca bn bit rng n nn trnh s dng cc cuc gi mi hn. Gi s class ny mi c thm vo: public class NewClass { private static int mDiv = 1; private int mMult; public static void setGlobalDiv(int div) { mDiv = div; } public NewClass(int mult) {

mMult = mult; } public int doStuff(int val) { return (val * mMult) / mDiv; } } Chng ta s to ra mt lp wrapper cho n: class WrapNewClass { private NewClass mInstance; /* class initialization fails when this throws an exception */ static { try { Class.forName("NewClass"); } catch (Exception ex) { throw new RuntimeException(ex); } } /* calling here forces class initialization */ public static void checkAvailable() {} public static void setGlobalDiv(int div) { NewClass.setGlobalDiv(div); } public WrapNewClass(int mult) { mInstance = new NewClass(mult); } public int doStuff(int val) { return mInstance.doStuff(val); } } iu ny c mt method cho mi constructor v method trong initializer, cng vi static initializer m tests cho s hin din ca class mi. Nu lp mi khng c, initialization ca WrapNewClass khng thnh cng, m bo rng cc class wrapper khng th c s dng v tnh. The checkAvailable method is used as a simple way to force class initialization. Cc phng php checkAvailable c s

dng nh l mt cch n gin n class initialization. Chng ti s dng n nh th ny: public class MyApp { private static boolean mNewClassAvailable; /* establish whether the "new" class is available to us */ static { try { WrapNewClass.checkAvailable(); mNewClassAvailable = true; } catch (Throwable t) { mNewClassAvailable = false; } } public void diddle() { if (mNewClassAvailable) { WrapNewClass.setGlobalDiv(4); WrapNewClass wnc = new WrapNewClass(40); System.out.println("newer API is available wnc.doStuff(10)); } else { System.out.println("newer API not available"); } } }

"

Nu cuc gi n checkAvailable thnh cng, chng ta bit nhng class mi l mt phn ca h thng. Nu khng, chng ti bit nhng lp hc khng phi, v sa cha cho ph hp. Cn lu rng cc cuc gi n checkAvailable s khng thnh cng trc khi n bt u ngay c nu bytecode quyt nh rng n khng mun chp nhn mt class m c tham chiu n mt class khng tn ti. Cch m ny c cu trc, kt qu cui cng l trng hp ngoi l nh nhau cho d n t cc xc hoc t cc cuc gi n Class.forName Khi wrapping mt class by gi c mt phng php mi, bn ch cn a cc phng php mi vo lp wrapper. Gi trc tip cc method c. Cc initializer static trong WrapNewClass s c tng cng lm mt thi gian kim tra vi reflection. Th nghim l cha kha

Bn phi th nghim ng dng ca bn trn tt c cc phin bn ca Android framework m d kin s h tr n. Theo nh ngha, trn mi hnh vi ng dng ca bn s khc nhau. Bn nn nh rng: nu bn khng th n, n khng hot ng. Bn c th kim tra tnh tng thch ngc bng cch chy ng dng ca bn trong mt m phng s dng mt phin bn c hn ca nn tng ny. Android SDK cho php bn lm iu ny mt cch d dng bng cch to ra "Thit b Android o" vi API mc khc nhau. Mt khi bn to AVDs, bn c th th nghim ng dng ca bn vi phin bn c v mi ca h thng, c l n chy side-by-side xem s khc bit. Thng tin thm v AVDs gi lp c th c tm thy trong ti liu AVD v t emulator -help-virtual-device Tm hiu qun l thit b trong Android Android 2,2 gii thiu h tr cho cc ng dng doanh nghip bng cch cung cp cc thit b Android chnh API. Cc thit b chnh API cung cp cc tnh nng qun l thit b cp h thng. Nhng API ny cho php bn to cc ng dng bo mt bit rng c ch trong cc thit lp doanh nghip, trong cc chuyn gia CNTT cn kim sot nhiu hn cc thit b nhn vin. V d, xy dng trong ng dng Email Android tha hng cc API mi ci thin h tr Exchange. Thng qua ng dng Email, Exchange qun tr c th thc thi cc chnh sch mt khu - bao gm c ch v s mt khu hoc s PIN - qua nhiu thit b. Cc qun tr vin cng c th xa sch t xa (c ngha l, khi phc li mc nh nh my trn) thit b cm tay b mt hoc b nh cp. Exchange ngi dng c th ng b ha email ca h v d liu lch. Ti liu ny c thit k pht trin nhng ngi mun pht trin cc gii php doanh nghip cho cc thit b h tr Android. N bn v cc tnh nng khc nhau c cung cp bi chnh thit b API cung cp bo mt mnh m hn cho cc thit b nhn vin c trang b Android. Tng quan API qun l thit b Di y l v d v cc loi ng dng m c th s dng cc API thit b chnh : Email khch hng. An ninh ng dng m xa t xa. Thit b dch v qun l v ng dng. N lm vic nh th no ?

Bn s dng cc thit b API chnh vit cc ng dng thit b admin m ngi dng ci t trn thit b ca h. Cc ng dng thit b admin thc thi cc chnh sch mong mun. y l cch n hot ng: Mt vin qun tr h thng vit mt ng dng thit b admin m thc thi t remote/local chnh sch thit b an ninh. Nhng chnh sch ny c th c m ha cng vo ng dng, hoc cc ng dng t ng c th ly chnh sch t mt my ch ca bn th ba.

Cc ng dng c ci t trn thit b ca ngi dng. Android hin ti khng c mt gii php cung cp t ng. Mt s trong nhng cch mt qun tr h thng c th phn phi cc ng dng cho ngi dng nh sau: Android Market. Cho php ci t phi th trng.

Phn phi cc ng dng thng qua cc phng tin khc, chng hn nh email hoc cc trang web.

H thng nhc nh ngi dng kch hot cc thit b ng dng admin. Lm th no v khi iu ny xy ra ph thuc vo ng dng c thc hin. Mt khi ngi dng kch hot cc ng dng thit b admin, h c th chnh sch ca mnh. Tun th cc chnh sch thng trao li ch, chng hn nh truy cp vo cc h thng nhy cm v d liu.

Nu ngi dng khng cho php cc ng dng thit b admin, n vn cn trn thit b, nhng trong mt trng thi khng hot ng. Ngi dng s khng b p dng cc chnh sch ca mnh, v h s ngc li khng nhn c bt k ca cc ng dng ca cc li ch, v d, h c th khng c kh nng ng b ha d liu. Nu ngi dng khng tun th cc chnh sch (v d, nu ngi dng t mt khu m vi phm cc hng dn), l vo cc ng dng quyt nh cch x l ny. Tuy nhin, thng thng iu ny s dn n vic ngi dng khng th ng b ha d liu. Nu thit b ca mt n lc kt ni n mt my ch m khng i hi cc chnh sch h tr trong API qun l thit b, kt ni s khng c php. Cc API thit b chnh hin ti khng cho php cung cp mt phn. Ni cch khc, nu mt thit b (v d, mt thit b di sn) khng h tr tt c cc chnh sch quy nh, khng c cch no cho php cc thit b kt ni. Nu mt thit b cha nhiu kch hot cc ng dng qun tr, cc chnh sch kht khe c thi hnh. Khng c cch no nhm mc tiu mt ng dng c th admin.

g b ci t mt ng dng thit b hin c admin, ngi dng cn phi u tin ng k ca cc ng dng nh l mt qun tr vin. Chnh sch Trong cc thit lp doanh nghip, l trng hp thng thy cc thit b nhn vin phi tun th nghim ngt ca mt b chnh sch cai tr s dng ca thit b. Cc thit b chnh API h tr cc chnh sch c lit k trong Bng 1. Lu rng cc thit b hin hnh API ch h tr mt khu kha mn hnh:

Mt khu c kch hot: Yu cu cc thit b yu cu m PIN hay mt khu. Chiu di mt khu ti thiu: Thit lp s lng k t cho yu cu ca mt khu. V d, bn c th yu cu m PIN hoc mt khu c t nht su k t. Ch s mt khu yu cu Yu cu c mt khu c kt hp cc ch ci v s. H c th bao gm cc nhn vt tng trng. Ti a n lc khng thnh cng mt khu Ch nh bao nhiu ln mt ngi s dng c th nhp mt khu sai trc khi thit b lau d liu ca n. Cc thit b chnh API cng cho php qun tr t xa t li thit b mc nh ca nh my. iu ny m bo d liu trong trng hp in thoi b mt hoc b nh cp. Thit lp thi gian ti a khng hot ng kha chiu di ca thi gian k t khi ngi s dng cui cng chm vo mn hnh hoc n mt nt trc khi thit b kha mn hnh. Khi iu ny xy ra, ngi dng cn phi nhp m PIN hay mt khu ca mnh mt ln na trc khi h c th s dng thit b ca h v truy cp d liu. Gi tr c th c t 1 n 60 pht.

Cc tnh nng khc Ngoi vic h tr cc chnh sch c lit k trong bng trn, cc thit b chnh API cho php bn lm nh sau:

Nhc nh ngi dng thit lp mt mt khu mi.

Kha thit b ngay lp tc. Xa cc d liu ca thit b (c ngha l, khi phc li cc thit b v mc nh ca n). Pht trin Android trong cc IDE khc Khuyn ngh nn pht trin mt ng dng Android l s dng Eclipse vi plugin ADT .. Cc plugin ADT cung cp chnh sa, xy dng, g li, v ng gi apk v chc nng k quyn tch hp vo IDE.

Tuy nhin, nu bn thch pht trin cc ng dng ca bn trong mt IDE, nh IntelliJ, hoc trong mt trnh son tho c bn, chng hn nh Emacs, bn c th lm iu thay th. SDK ny bao gm tt c cc cng c bn cn thit lp mt d n Android, xy dng n, g li n v sau ng gi phn phi. This document is your guide to using these tools. Ti liu ny l hng dn ca bn s dng nhng cng c ny.

Cng c cn thit Khi pht trin trong cc IDE hoc bin tp vin khc so vi Eclipse, bn s yu cu s quen thuc vi cng c SDK Android sau y: Android to / cp nht cc d n Android v to / di chuyn / xa AVDs. Android Emulator chy cc ng dng Android ca bn trn mt nn tng Android m phng. Android Debug Bridge giao tip vi gi lp ca bn hoc kt ni thit b (ci t cc ng dng, v cc thit b, ban hnh lnh, vv.) Ngoi cc cng c trn, bao gm trong cc SDK, bn s s dng m ngun m sau v bn th ba cng c: Ant : bin dch v xy dng d n Android ca bn thnh mt file apk ci t.. Keytool Keytool :

to mt kho keystore v t nhn, s dng ng file apk. Ca bn. Jarsigner (hoc tng t nh cng c ch k) .

ng file apk. Ca bn vi mt kha ring c to ra bi keytool. Trong cc ch tip theo, bn s c gii thiu vi mi cng c ny l cn thit,. nng cao hn na cc hot ng xin vui lng c ti liu tng ng cho mi cng c. To mt d n Android

to mt d n Android, bn phi s dng android cng c. Khi bn to mt d n mi vi android , n s to ra mt th mc d n vi mt s tp tin ng dng mc nh, cc tp tin cn s khai, cc file cu hnh v xy dng mt tp tin. To mt d n mi Nu bn ang bt u mt d n mi, s dng android create project lnh to ra tt c cc file cn thit v th mc.

to mt d n Android mi, m ra mt dng lnh, iu hng n cc tools/ th mc ca bn chy SDK v: android create project \ --target <target_ID> \ --name <your_project_name> \ --path path/to/your/project \ --activity <your_activity_name> \ --package <your_package_namespace>

target l "xy dng mc tiu" cho ng dng ca bn. N tng ng vi mt th vin nn tng Android (bao gm bt k tin ch, chng hn nh Google API) m bn mun xy dng cc d n ca bn chng li. xem danh sch cc mc tiu c sn v cc ID tng ng ca h, thc hin: android list targets . name l tn cho d n ca bn. Nu cung cp, tn ny s c s dng cho apk. Bn tn tp tin khi bn xy dng ng dng ca bn. path l v tr ca th mc d n ca bn. Nu cc th mc khng tn ti, n s c to ra cho bn. activity l tn mc nh ca bn Activity lp. y lp tp tin s c to ra cho bn bn trong /src/ / . iu ny cng s c s dng cho apk. bn tn tp tin, tr khi bn cung cp mt cc name . package l cc khng gian tn gi cho d n ca bn, theo cc quy tc tng t nh i vi cc gi ngn ng lp trnh Java. y l v d:

Di

android create project \ --target 1 \ --name MyAndroidApp \ --path ./MyAndroidAppProject \ --activity MyAndroidAppActivity \ --package com.example.myandroid Cng c ny to ra cc tp tin v th mc sau y:

AndroidManifest.xml - Cc biu hin tp tin ng dng, ng b ha vi lp cui quy nh cho d n. build.xml - Xy dng cc tp tin cho Ant. default.properties - cho xy dng. h thng properties khng sa i tp tin ny.

build.properties - tnh ty bin cho vic xy dng h thng. Bn c th chnh sa file ny ghi ln cc thit lp mc nh xy dng c s dng bi Ant v cung cp mt con tr ti keystore ca bn v b danh ch cht xy dng cc cng c c th ng k ng dng ca bn khi c xy dng trong ch pht hnh. src /your/package/namespace/ActivityName .java - The Activity class you specified during project creation. src /your/package/namespace/ActivityName .java - Cc lp cui bn ch nh trong vic to ra d n. bin/ - Output directory for the build script. bin/ gen/ - Gi Ant -to ra cc tp tin, chng hn nh R.java . libs/ - Gi tin th vin. res/ - Gi ngun lc d n. src/ - Gi m ngun. tests/ - Gi mt bn sao ca tt c cc-of-the trn, cho mc ch th nghim.

Mt khi bn to ra d n ca bn, bn sn sng bt u pht trin. Bn c th di chuyn th mc d n ca bn bt c ni no bn mun pht trin, nhng hy nh rng bn phi s dng Android Debug Bridge (adb) - nm trong SDK tools/ th mc - gi n ca bn trnh gi lp (c tho lun sau). V vy, bn cn truy cp gia cc gii php d n ca bn v cc tools/ th mc. Ch : Bn nn hn ch di chuyn v tr ca th mc SDK, v iu ny s ph v xy dng kch bn. (H s cn phi t cp nht phn nh v tr SDK mi trc khi h s lm vic mt ln na.)

Thay i tiu ca s trong Android Thay i tiu ca s trong mt hot ng hay trn trn ton b ng dng ca bn c v n gin, nhng c rt t ti liu vit v n v lm cho n xy ra. Bn cn phi xc nh kiu ty bin v p dng nhng phong cch cho mt ch ty chnh. iu ny c t trong mt ti liu xml trong th mc "value". Trong bn demo ca n c gi l custom_styles.xml. Tn gi ny l ty bn c th thay i.

<!-- Sets the text styles --> <?xml version="1.0" encoding="utf-8"?> <!-- Sets the text styles --> <resources> <style name="CustomWindowTitleText" parent="android:TextAppearance.WindowTitle"> <item name="android:textSize">20dip</item> <item name="android:textColor">#5599FF</item> <item name="android:textStyle">bold| italic</item> </style> <!-- Changes the background color of the title bar --> <style name="CustomWindowTitleBackground"> <item name="android:background">#222222</item> </style> <!-- Set the theme for the window title --> <!-- NOTE: setting android:textAppearence to style defined above --> <style name="CustomWindowTitle" parent="android:WindowTitle"> <item name="android:textAppearance">@style/CustomWindowTitleT ext</item> <item name="android:shadowDx">0</item> <item name="android:shadowDy">0</item> <item name="android:shadowRadius">5</item>

name="android:shadowColor">#1155CC</item> </style> <!-- Override properties in the default theme --> <!-NOTE: you must explicitly the windowTitleSize property, the title bar will not resize automatically, text will be clipped --> <style name="CustomTheme" parent="android:Theme"> <item name="android:windowTitleSize">40dip</item> <item name="android:windowTitleStyle">@style/CustomWindowTitl e</item> <item name="android:windowTitleBackgroundStyle">@style/Custom WindowTitleBackground</item> </style> </resources> Lastly, to make the change take affect you need to set the theme in the manifest file. <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/CustomTheme"> Lm th no s dng ProgressBar trong Android? ProgressBar l mt ch bo trc quan m t mt hnh ng. N hin th cho ngi dng cc hnh ng ang tin trin, cc ng dng c th thay i ch s tng gim khi n di chuyn v pha trc hoc pha sau.

<item

v d ny ti dng implemenets mt ProgressBar vng trn mc nh v mt ProgressBar ngang. i vi cc ProgressBar ngang, mt ch Runnable c thc hin gi tin nhn n mt x l tng tng hoc gim cc ch s ca ProgressBar. Thit lp thng s cho main.xml : < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > < TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> < ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressbar_default" /> < ProgressBar android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" android:id="@+id/progressbar_Horizontal" android:max="100" /> Code cho Activity : package com.android.sample.AndroidProgressBar;

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ProgressBar;

public class AndroidProgressBar extends Activity { ProgressBar myProgressBar; int myProgress = 0;

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal); new Thread(myThread).start(); }

private Runnable myThread = new Runnable(){ @Override public void run() { // TODO Auto-generated method stub while (myProgress<100){ try{ myHandle.sendMessage(myHandle.obtainMessage()); Thread.sleep(1000); } catch(Throwable t){ } } }

Handler myHandle = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub myProgress++; myProgressBar.setProgress(myProgress); }

}; }; } Code hon tt, bn c th run v xem kt qu th no. Lm th no s dng SeekBar trong Android SeekBar l mt m rng ca ProgressBar m Android h tr c th ty chnh trc tip. Ngi dng c th ko sang tri hoc phi thit lp mc ch s hin ti hoc s dng cc phm mi tn.

Thit lp thng s cho Main.xml : < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > < TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> < SeekBar android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10px" android:id="@+id/seekbar" android:max="100" android:progress="50" /> < TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/seekbarvalue" android:text="50" />

Code cho Activity :

package com.AndroidSeekBar;

import android.app.Activity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.TextView;

public class AndroidSeekBar extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

SeekBar seekBar = (SeekBar)findViewById(R.id.seekbar); final TextView seekBarValue = (TextView)findViewById(R.id.seekbarvalue);

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub seekBarValue.setText(String.valueOf(progress)); }

@Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub

@Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } }); } } Lm th no s dng RatingBar trong Android? Mt RatingBar l mt m rng ca SeekBar v ProgressBar th hin mt nh gi trong cc ngi sao. Ngi dng c th chm/ko hoc s dng cc phm mi tn thit lp cc nh gi khi s dng RatingBar kch thc mc nh. Cc RatingBar nh hn theo phong cch (ratingBarStyleSmall) v phong cch ch th, ch ln hn (ratingBarStyleIndicator) khng h tr tng tc ngi dng v ch nn c s dng nh l cc ch s.

Thit lp thng s cho Main.xml : < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > < TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

< RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content" style="? android:attr/ratingBarStyleSmall" android:id="@+id/ratingbar_Small" android:numStars="20" /> < RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content" style="? android:attr/ratingBarStyle" android:id="@+id/ratingbar_default" />

Code Activity : package com.android.sample.AndroidRatingBar; import android.app.Activity; import android.os.Bundle; import android.widget.RatingBar; import android.widget.Toast; public class AndroidRatingBar extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final RatingBar ratingBar_Small = (RatingBar)findViewById(R.id.ratingbar_Small); final RatingBar ratingBar_Indicator = (RatingBar)findViewById(R.id.ratingbar_Indicator); final RatingBar ratingBar_default = (RatingBar)findViewById(R.id.ratingbar_default); ratingBar_default.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){ @Override public void onRatingChanged(RatingBar ratingBar, float rating,

boolean fromUser) { // TODO Auto-generated method stub ratingBar_Small.setRating(rating); ratingBar_Indicator.setRating(rating); Toast.makeText(AndroidRatingBar.this, "rating:"+String.valueOf(rating), Toast.LENGTH_LONG).show(); }}); } } Lm th no ti d liu RSS trong Android V d ny ti mun cho cc bn bit lm th no? ti d liu t rss trong Android. y ch l phn c bn trong x l d liu ng, bn c th dng nhiu d liu khc nhau.

Khi demo c run, mn hnh u tin ti c nh trn. By gi ti bt u code cho demo, trc tin ti thit lp mt s thng s cho mt vi xml: i vi AndroidManifest.xml : <?xml version="1.0" encoding="utf-8"?> <!-- Declare the contents of this Android application. The namespace attribute brings in the Android platform namespace, and the package supplies a unique name for the application. When writing your own application, the package

name must be changed from "com.example.*" to come from a domain that you own or have control over. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.sample.rss" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="RssReader"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> </manifest> Trong folder layout ti rename main.xml = rss_layout.xml v thng s nh sau : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dip" android:orientation="vertical"> <EditText android:id="@+id/urltext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="12sp" android:autoText="false"

android:capitalize="none" android:text="@string/rss_layout_urltext_text" /> <Button android:id="@+id/download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rss_layout_download_text" /> <TextView android:id="@+id/statustext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoText="false" android:capitalize="none" android:textSize="12sp" android:text="@string/rss_layout_statustext_text" /> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:drawSelectorOnTop="false" /> </LinearLayout> Sau khi cc thit lp v code cho activity hon tt, kt qu ti c khi run demo nh sau :

Lm th no xy dng t in tm kim trong Android

Mt ng dng mu c th hin tm kim ca Android. ng dng ny bao gm mt t in cc t. Bng cch gi hp thoi tm kim bn trong cc ng dng Android (thng qua cc nt tm kim thit b hoc Menu> Search), bn c th thc hin tm kim trn t in. Khi bn nhp, gi s xut hin, m bn c th chn xem nh ngha hon chnh. Bn cng c th thc hin tm kim xem tt c cc nh ngha t ph hp vi vn bn nhp vo. ng dng ny cng cho php Quick Search Box (ton h thng tm kim ca Android) cung cp t in ngh. Mn hnh sau cho cc bn bit sau khi setup project hon chnh.

Khi ban click vao button t in tm kim v mn hnh k tip bn s thy nh sau :

Sau khi bn lick tm kim

Khi bn g bt c mt k t no , chng trnh s a ra nhng gi bng nhng t c k t u bng k t m bn g vo. y ti s g a bn xem th no?

Bn c th thm t, t file /res/raw/definitions.txt. Source SVN : http://kythuatlaptrinh.googlecode.com/svn/trunk/mobile/android/SampleSearchabl eDictionary/ Cch s dng ContentProvider trong Android

ContentProvider l nn tng Android cch chia s thng tin gia nhiu ng dng thng qua giao din ContentResolver ca n. Mi ng dng c quyn truy cp c s d liu SQLite duy tr thng tin ca h v iu ny khng th chia s vi cc ng dng khc. Trong bn demo ny, chng ti s dng thng tin cung cp ni dung avaialable qua getContentResolver() c c thng tin thit b vi cc trng hp contentresolver v quierying cung cp con tr. Ngoi vic truy vn, bn c th dng vi cc phng php lin quan, kh nng chn, cp nht, xa v getType ( trch xut cc loi nh dng). Kt qu cui cng l danh sch ca h thng tt c cc thit lp v ngi s dng trn thit b Android. Vi d SimpleCursorAdapter lm cho vic s dng ca row.xml vi thng tin con tr nh c trong ListView trong b tr main.xml. Code cho ContentUserDemo.java

import android.app.Activity; import android.content.ContentResolver; import android.database.Cursor; import android.os.Bundle; import android.provider.Settings;

import android.util.Log; import android.widget.ListView; import android.widget.SimpleCursorAdapter;

public class ContentUserDemo extends Activity { private static final String TAG = "ContentUserDemo";

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

// Get content provider and cursor ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(Settings.System.CONTENT_URI, null, null, null, null);

// Let activity manage the cursor startManagingCursor(cursor); Log.d(TAG, "cursor.getCount()=" + cursor.getCount());

// Get the list view ListView listView = (ListView) findViewById(R.id.listView); String[] from = { Settings.System.NAME, Settings.System.VALUE }; int[] to = { R.id.textName, R.id.textValue }; SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.row, cursor, from, to); listView.setAdapter(adapter); } }

Ngoi cc thit lp chnh cho AndroidManifest.xml. ng qun thm th sau y cung cp cho ngi s dng truy cp cc thng tin lin lc. <uses-permission android:name="android.permission.READ_CONTACTS" /> Cu hnh file: AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.sample" android:versionCode="1" android:versionName="1.0.0"> <uses-permission android:name="android.permission.READ_CONTACTS" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ContentUserDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Thm row.xml cho demo <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:padding="5sp" android:layout_width="fill_parent"> <TextView android:layout_height="wrap_content"

android:id="@+id/textName" android:text="Name" android:textSize="18sp" android:layout_width="fill_parent" android:layout_weight="1"></TextView> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textValue" android:text="Value" android:textSize="18sp" android:gravity="right"></TextView> </LinearLayout> Cu hnh main.xml <?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"> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/listView"> </ListView> </LinearLayout> Lm th no s dng cm ng a im (Multi touch) Android Gii thiu cm ng a im : Multi-touch l ch n gin l mt phn m rng ca giao din ngi dng thng thng mn hnh cm ng, s dng hai hay nhiu ngn tay thay v mt. Chng ti s dng mt ngn tay c ch trc y, mc d chng ti khng gi n l. Trong Chng 4, chng ti cho php ngi dng chm vo mt gch trong cc tr chi Sudoku thay i n. l gi l "vi" c ch. C ch khc l c gi l "ko". l ni m bn gi mt ngn tay trn mn hnh v di chuyn n xung quanh, gy ra cc ni dung theo ngn tay ca bn di chuyn.

Tp, ko, v mt vi c ch khc duy nht-ngn lun lun c c h tr Android. Nhng do s ph bin ca iPhone Apple, ngi dng Android u b mt loi c ch ghen t. IPhone h tr a cm ng, trong "pinch zoom" nhng c ch c th.

Vi pinch phng to, bn t hai ngn tay trn mn hnh v p chng li vi nhau lm cho cc mc m bn ang xem nh hn, hoc ko chng ra lm cho n ln hn. Trc khi Android 2.0 bn phi s dng mt clunky iu khin zoom vi cc biu tng m bn p phng to ra (v d cc setBuiltInZoomControls() trong v d MyMap). Nhng nh c s h tr a cm ng mi ca n, bn c th kp phng to trn Android qu! Khi ng dng h tr n, tt nhin. Lu : Nu bn c gng chy cc v d trong chng ny trn Android 1.5 hoc 1.6, n s sp v nhng phin bn khng h tr a cm ng. Chng ti s tm hiu lm th no lm vic xung quanh m trong chng 13, "Vit mt ln, mi ni th nghim". Cnh bo: Multi-li trc Multi-touch, nh thc hin trn in thoi Android hin ti c li. Trong thc t n rt nhiu li m n khng s dng c. API ny thng xuyn bo co d liu khng hp l hoc khng th im, c bit l trong qu trnh chuyn i t mt ngn tay vo hai ngn tay trn mn hnh v ngc li. Trn cc din n pht trin bn c th tm thy khiu ni ca cc ngn tay b i ch, cc trc x v y lt, v nhiu ngn tay i khi b i x nh l mt. Vi rt nhiu th v sai, ti c th c c nhng v d trong chng ny lm vic bi v cc c ch thc hin rt n gin. Cho n khi Google cng nhn v sa

cha cc vn , thatmay c v tt c cc bn c th lm. May mn thay, nhn nhm zoom dng nh l ch a chm c ch hu ht mi ngi mun. V d Touch chng minh a cm ng, chng ta s xy dng mt ng dng xem nh n gin cho php bn phng to v di chuyn xung quanh mt hnh nh. Xy dng v d Touch trong Android Phn 2 chng minh a cm ng, chng ta s xy dng mt ng dng xem nh n gin cho php bn phng to v di chuyn xung quanh mt hnh nh. Bt u bng cch to ra mt "Hello, Android" d n vi cc thng s sau trong hp thoi Android mi d n: Tn d n: Touch Xy dng cc mc tiu: Android 2.1 ng dng hiu: Touch ng gi v tn: org.example.touch To cui: Touch iu ny s to Touch.java cha cc hot ng chnh ca bn. Hy chnh sa n hin th mt hnh nh mu, t trong mt ngi nghe cm ng, v thm mt vi nhp khu chng ti s cn sau: t Touchv1/src/org/example/touch/Touch.java: package org.example.touch; import android.app.Activity; import android.graphics.Matrix; import android.graphics.PointF; import android.os.Bundle; import android.util.FloatMath; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class Touch extends Activity implements OnTouchListener {

private static final String TAG = "Touch" ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView view = (ImageView) findViewById(R.id.imageView); view.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { // Handle touch events here... } } Chng ta s lm ra rng onTouch() trong giy lt. Trc tin chng ta cn nh ngha b tr cho hot ng ca chng ta: T Touchv1/res/layout/main.xml: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/butterfly" android:scaleType="matrix" > </ImageView> </FrameLayout> Giao din ton b l mt ImageView kim sot ln bao gm ton b mn hnh. Cc android:src="@drawable/butterfly" gi tr cp n hnh nh con bm c s dng trong v d. Bn c th s dng bt k nh dng hnh nh JPG hoc PNG bn thch, ch cn t n trong th mc res/drawables-nodpi. Cc android:scaleType="matrix" cho thy chng ta s s dng mt ma trn kim sot v tr v quy m ca hnh nh. Thm v iu ny sau. Cc tp tin AndroidManifest.xml l b nh hng tr vic b sung cc android:theme T Touchv1/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.example.touch" android:versionCode="1" android:versionName="1.0" > <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" > <activity android:name=".Touch" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="7" /> </manifest> @android:style/Theme.NoTitleBar.Fullscreen nh tn cho thy, cho Android s dng ton b mn hnh khng c thanh tiu hoc thanh trng thi u trang. Bn c th chy cc ng dng hin nay v n ch n gin s hin th hnh nh. Tm hiu v cc s kin touch trong Android Bt c khi no ln u tin ti tm hiu mt API mi, ti mun t u tin trong m s tt c mi th v vy ti c th nhn c mt cm gic v nhng g cc phng php lm v trong nhng s kin g xy ra. V vy, hy bt u vi iu . Thm u mt cuc gi n dumpEvent() phng php bn trong onTouch(): T Touchv1/src/org/example/touch/Touch.java: @Override public boolean onTouch(View v, MotionEvent event) { // Dump touch event to log dumpEvent(event); return true; // indicate event was handled }

Lu rng chng ta cn phi tr v ng vi ch s cho Android rng s kin ny c x l. Tip theo, xc nh cc method dumpEvent(). Cc tham s ch l s kin m chng ta mun dump. T Touchv1/src/org/example/touch/Touch.java: /** Show an event in the LogCat view, for debugging */ private void dumpEvent(MotionEvent event) { String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" , "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" }; StringBuilder sb = new StringBuilder(); int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; sb.append("event ACTION_" ).append(names[actionCode]); if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) { sb.append("(pid " ).append( action >> MotionEvent.ACTION_POINTER_ID_SHIFT); sb.append(")" ); } sb.append("[" ); for (int i = 0; i < event.getPointerCount(); i++) { sb.append("#" ).append(i); sb.append("(pid " ).append(event.getPointerId(i)); sb.append(")=" ).append((int) event.getX(i)); sb.append("," ).append((int) event.getY(i)); if (i + 1 < event.getPointerCount()) sb.append(";" ); } sb.append("]" ); Log.d(TAG, sb.toString()); } Kt qu s i n cc bn ghi g li Android, bn c th nhn thy bng cch m xem LogView. Cch d nht hiu on m ny l chy n. Tht khng may bn khng th chy chng trnh trn Emulator (thc ra bn c th, nhng cc Emulator khng h tr a cm ng nh vy kt qu s khng c rt th v). V vy, hy lm vi mt in thoi thc s vi cng USB ca bn v chy cc mu c.

Lm th no s dng cm bin trong Android B cm bin h tr Android l kh n gin nhng a nng. N c x l qua cc SensorManager c cung cp t ng cnh ng dng ca bn thng qua getSystemService(). Mt khi bn qun l b cm bin, bn phi ng k nhn thng bo ca mnh. lm iu ny, chng ti thc hin cc giao din SensorListener. Ch rng chng ti ng k nhn c cp nht cm bin trong onResume() v hu ng k trong onPause(). iu ny l quan trng. Cm bin d liu n trong khong thi gian tht thng v c th tiu tn rt nhiu CPU v nng lng pin. ng dng ti u ha ca chng ti thc hin, l thc hnh tt nht c c cc thng bo ch khi ng dng ca bn l trong iu hnh nh nc. Cc thng bo n qua onSensorChanged() v onAccuracyChanged(). Ch rng mi mt tham s cho cc bo co cm bin. Android API cm bin c th h tr mt s lng ln cc b cm bin, mi ngi c ring ID s nguyn duy nht ca n. Nhng ngi hin ti c th hin qua cc hng s ca h, chng hn nh SensorManager.SENSOR_ORIENTATION. Cm bin Cc gi tr chng ta c c trong onSensorChanged() s ph thuc vo cm bin c th. V d, nh hng cm bin bo co phng v l gi tr ch s 0, sn ch s 1 v cun vo ch s Code: SensorsDemo.java package com.android.sample; import android.app.Activity; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class SensorDemo extends Activity implements SensorListener { private static final String TAG = "SensorDemo"; private SensorManager sensorManager; private TextView outView; private int sensor = SensorManager.SENSOR_ORIENTATION;

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); outView = (TextView) findViewById(R.id.output); // Real sensor manager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); } /** Register for the updates when Activity is in foreground */ @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); sensorManager.registerListener(this, sensor); } /** Stop the updates when Activity is paused */ @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); sensorManager.unregisterListener(this, sensor); } public void onAccuracyChanged(int sensor, int accuracy) { Log.d(TAG, String.format("onAccuracyChanged sensor: %d accuraccy: %d", sensor, accuracy)); } public void onSensorChanged(int sensorReporting, float[] values) { if (sensorReporting != sensor) return;

float azimuth = Math.round(values[0]); float pitch = Math.round(values[1]); float roll = Math.round(values[2]); String out = String.format("Azimuth: %.2f\n\nPitch:%.2f\nRoll", azimuth, pitch, roll); Log.d(TAG, out); outView.setText(out); } } Cch b tr cho v d n gin chi c cha mt TextView cho u ra. Code: /res/layout/main.xml <?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"> <TextView android:id="@+id/output" android:layout_width="fill_parent" android:text="@string/hello" android:textSize="24sp" android:layout_height="fill_parent" android:layout_margin="30dp" /> </LinearLayout> Ch rng cm bin trong cc gi lp khng c h tr. C mt cch thng qua mt cng c OpenIntents, nhng i hi mt cht v thit lp. y l nhng g u ra trng ging nh trn thit b tht:

Thc hin giao din t xa s dng AIDL AIDL (Android Interface Definition Language) l mt ngn ng IDL c s dng to ra m cho php hai qu trnh trn mt thit b h tr Android ni chuyn bng cch s dng giao tip InterProcess (IPC). Nu bn c m trong mt qu trnh (v d, trong mt hot ng) m cn phi gi cc phng thc trn mt i tng trong qu trnh khc (v d, mt dch v), bn s s dng AIDL to ra m marshall cc thng s. Cc c ch AIDL IPC l da trn giao din, tng t nh COM hay CORBA, nhng trng lng nh hn. N s dng mt lp proxy vt qua gi tr gia khch hng v thc hin. Mi ng dng Android chy trong qu trnh ring ca mnh. Mt ng dng khng th trc tip truy cp khng gian b nh khc ca ng dng. y l ng dng gi l sandboxing. Xc nh AIDL C php AIDL rt ging vi giao din Java thng xuyn. Bn ch cn xc nh phng php ch k. Cc kiu d liu c h tr bi AIDL l hi khc so vi thng thng giao din Java. i vi mt, tt c cc kiu d liu nguyn thy c h tr Java. V vy, l String, Danh sch, bn , v CharSequence cc lp hc. Ngoi ra, tt c cc kiu d liu AIDL khc m bn nh ngha c h tr. Thm vo , tt c cc lp Parcelable c h tr, nhng iu ny s khng c

cp trong v d ny. Ti ang c gng gi cho v d ny kh n gin bt u. Code: /src/com.android.sample/IAdditionService.aidl package com.android.sample; // Declare the interface. interface IAdditionService { // You can pass values in, out, or inout. // Primitive datatypes (such as int, boolean, etc.) can only be passed in. int add(in int value1, in int value2); } Thc hin cc dch v t xa Mt khi bn to ra file AIDL ca bn v t n vo ng ch, cng c Eclipse + AIDL s to ra mt file c cng tn, nhng phn m rng. java. V vy, ti by gi c file /gen/com.android.sample/IAdditionService.java. y l mt tp tin t ng to ra do bn khng mun chnh sa n. iu quan trng l n c cha mt lp Stub rng chng ti s mun thc hin cho cc dch v t xa ca chng ti. thc hin cc dch v t xa ca chng ta, chng ta s tr li IBinder t onBind() trong lp dch v AdditionService. IBinder i din cho vic thc hin cc dch v t xa. thc hin IBinder, chng ta phn lp IAddtionService.Stub lp t m Java t ng to ra, v cung cp thc hin cc phng php ca chng ti AIDL xc nh, trong trng hp tin ch ny Add(). Code : /src/com.android.sample/AdditionService.java import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * This class exposes the remote service to the client */ public class AdditionService extends Service {

private static final String TAG = "AdditionService"; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate()"); } @Override public IBinder onBind(Intent intent) { return new IAdditionService.Stub() { /** * Implementation of the add() method */ public int add(int value1, int value2) throws RemoteException { Log.d(TAG, String.format("AdditionService.add(%d, %d)",value1, value2)); return value1 + value2; } }; } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); } } Phi by cc dch v cc b Mt khi chng ta c cc dch v thc hin cc onBind() ng cch, chng ta sn sng kt ni vi dch v t khch hng ca chng ta. Trong trng hp ny, chng ta AIDL Demo hot ng kt ni vi dch v . thit lp kt ni, chng ta cn phi thc hin cc lp ServiceConnection. Hot ng trong v d ny cung cp ny thc hin trong lp AdditionServiceConnection bn trong bng cch thc hin onServiceConnected() v phng php onServiceDiconnected(). Nhng callback s c thc hin s khai ca cc dch v t xa khi kt ni. Chng ta cn phi b chng t khai thc hin dch v AIDL ca chng ti. lm c iu , chng ti s dng

IAdditionService.Stub.asInterface((IBinder) boundService) phng php gip . T thi im ny, chng ta c mt i tng dch v a phng m chng ta c th s dng thc hin cuc gi i vi cc dch v t xa. Code: /src/com.android.sample/AIDLDemo.java package com.android.sample; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class AIDLDemo extends Activity { private static final String TAG = "AIDLDemo"; IAdditionService service; AdditionServiceConnection connection; /** * This class represents the actual service connection. It casts the bound * stub implementation of the service to the AIDL interface. */ class AdditionServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { service = IAdditionService.Stub.asInterface((IBinder) boundService); Log.d(AIDLDemo.TAG, "onServiceConnected() connected");

Toast.makeText(AIDLDemo.this, "Service connected", Toast.LENGTH_LONG) .show(); } public void onServiceDisconnected(ComponentName name) { service = null; Log.d(AIDLDemo.TAG, "onServiceDisconnected() disconnected"); Toast.makeText(AIDLDemo.this, "Service connected", Toast.LENGTH_LONG).show(); } } /** Binds this activity to the service. */ private void initService() { connection = new AdditionServiceConnection(); Intent i = new Intent(); i.setClassName("com.marakana", com.marakana.AdditionService.class.getName()); boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE); Log.d(TAG, "initService() bound with " + ret); } /** Unbinds this activity from the service. */ private void releaseService() { unbindService(connection); connection = null; Log.d(TAG, "releaseService() unbound."); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initService();

// Setup the UI Button buttonCalc = (Button) findViewById(R.id.buttonCalc); buttonCalc.setOnClickListener(new OnClickListener() { TextView result = (TextView) findViewById(R.id.result); EditText value1 = (EditText) findViewById(R.id.value1); EditText value2 = (EditText) findViewById(R.id.value2); public void onClick(View v) { int v1, v2, res = -1; v1 = Integer.parseInt(value1.getText().toString()); v2 = Integer.parseInt(value2.getText().toString()); try { res = service.add(v1, v2); } catch (RemoteException e) { Log.d(AIDLDemo.TAG, "onClick failed with: " + e); e.printStackTrace(); } result.setText(new Integer(res).toString()); } }); } /** Called when the activity is about to be destroyed. */ @Override protected void onDestroy() { releaseService(); } } Cc giao din ngi dng trong trng hp ny rt n gin. C vi EditText TextViews v cc lnh vc v mt nt nt ny x l cc s kin ca n trong mt bn trong lp OnClickListener v danh. Nt ny ch n gin gi cc tin ch () phng thc dch v ny nh th n l mt cuc gi a phng. Cch b tr cho v d ny khng phi l quan trng, nhng ti bao gm n y cho mc ch hon thin. Code: /res/layout/main.xml <?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"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="AIDL Demo" android:textSize="22sp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/value1" android:hint="Value 1" /> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:textSize="36sp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/value2" android:hint="Value 2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonCalc" android:text="=" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="result" android:textSize="36sp" android:id="@+id/result" /> </LinearLayout> Kt qu ti c khi Run demo ;

Kim tra v nhc nh bt s dng GPS kim tra xem GPS c kch hot hay khng, cc m sau y c th c s dng: String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); Nu l trng rng, c ngha l GPS cha c kch hot. Bn c th bt u hot ng vi Settings.ACTION_SECURITY_SETTINGS nh, chuyn sang trang thit lp GPS.

Nu tnh nng GPS c thit lp, khi y demo se bo cho bn bit nh sau :

Vi mt t code sau s gip bn kim tra tnh nng ny : import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.widget.Toast;

public class AndroidEnableGPS extends Activity {

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CheckEnableGPS(); }

private void CheckEnableGPS(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.equals("")){ //GPS Enabled Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider, Toast.LENGTH_LONG).show(); }else{ Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); startActivity(intent); } } } Lm th no chi MIDI m thanh s dng MediaPlayer Lp MediaPlayer c th c s dng kim sot pht li cc tp tin audio/video t file hay d liu.

t mt file MIDI vo res/raw th mc ca d n ca bn, ni m cc Eclipse plugin (hoc aapt) s tm thy n v lm cho n thnh mt ngun ti nguyn c th c tham chiu t lp R ca bn. "midi_sound.mid" trong exercise. Sa i main.xml c hai nt bm chi v tm dng. <?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/play" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="- PLAY -" /> <Button android:id="@+id/pause"

android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="- PAUSE -" /> </LinearLayout> Sa i m ngun, AndroidAudioPlayer.java. package com.exercise.AndroidAudioPlayer;

import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast;

public class AndroidAudioPlayer extends Activity {

MediaPlayer mediaPlayer;

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

mediaPlayer = MediaPlayer.create(this, R.raw.midi_sound);

Button buttonPlay = (Button)findViewById(R.id.play); Button buttonPause = (Button)findViewById(R.id.pause); buttonPlay.setOnClickListener(buttonPlayOnClickListener);

buttonPause.setOnClickListener(buttonPauseOnClickListener); }

Button.OnClickListener buttonPlayOnClickListener = new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); Toast.makeText(AndroidAudioPlayer.this, "mediaPlayer.start()", Toast.LENGTH_LONG).show(); } } };

Button.OnClickListener buttonPauseOnClickListener = new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); Toast.makeText(AndroidAudioPlayer.this, "mediaPlayer.pause()", Toast.LENGTH_LONG).show(); } } }; }

Lm th no xy dng dch v bo ng dng AlarmManager

AlarmManager class cung cp truy cp vo cc dch v h thng bo ng. iu ny cho php bn ln lch cc ng dng ca bn chy vo mt s im trong tng lai. Ngay c khi bo thc tt, v c ng k vi dch v ca h thng, n s t ng khi ng ng dng khi n cha c chy. Trong bi ny, mt bo ng d kin l 10 giy s bt u mt dch v, MyAlarmService.

Sa i main.xml c hai nt Start v Cancel cc bo ng. <?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/startalarm" android:layout_width="fill_parent" android:layout_height="wrap_content"

android:text="Start" /> <Button android:id="@+id/cancelalarm" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Cancel" /> </LinearLayout> AndroidAlarmService.java, v cc hot ng chnh cho class. package com.android.sample.AndroidAlarmService;

import java.util.Calendar;

import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.widget.Button; import android.widget.Toast;

public class AndroidAlarmService extends Activity { private PendingIntent pendingIntent; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button buttonStart = (Button)findViewById(R.id.startalarm); Button buttonCancel = (Button)findViewById(R.id.cancelalarm);

buttonStart.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class); pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 10); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show(); }}); buttonCancel.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.cancel(pendingIntent); // Tell the user about what we did. Toast.makeText(AndroidAlarmService.this, "Cancel!", Toast.LENGTH_LONG).show(); }}); } } MyAlarmService.java, n s bt u trong 10 giy c kch hot bi SlarmManager package com.android.sample.AndroidAlarmService;

import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast;

public class MyAlarmService extends Service {

@Override public void onCreate() { // TODO Auto-generated method stub Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show(); }

@Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show(); return null; }

@Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show(); }

@Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show(); }

@Override public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show(); return super.onUnbind(intent); } } Cui cng, sa i AndroidManifest.xml lit k nh l dch v. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.sample.AndroidAlarmService" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AndroidAlarmService" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyAlarmService" /> </application>

<uses-sdk android:minSdkVersion="4" /> </manifest>

Xy dng ng dng n gin xem video (.3gp) trong Android Demo n gin xem video nh dng file (.3gp) trong Android

Code cho VideoActivity.java : package com.android.sample.video;

import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.MediaController; import android.widget.VideoView;

public class VideoActivity extends Activity { /** Called when the activity is first created. */ @Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); VideoView myVideoView = (VideoView) findViewById(R.id.videoview); String viewSource = "http://daily3gp.com/vids/747.3gp"; try { myVideoView.setVideoURI(Uri.parse(viewSource)); myVideoView.setMediaController(new MediaController(this)); myVideoView.requestFocus(); myVideoView.start(); } catch (Exception e) { Log.e("SampleVideo", "error: " + e.getMessage(), e); if (myVideoView != null) { myVideoView.stopPlayback(); } } } } Code cho AndroidManifest.xml : <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.sample.video" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".VideoActivity" android:label="Media/Video View"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

</application> <uses-permission android:name="android.permission.INTERNET" /> </manifest> Code cho main.xml : <?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"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <VideoView android:id="@+id/videoview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> Mt s v d v inputType trn EditText trong Android

<?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Ordinary EditText" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Password" /> <EditText android:password="true" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Multi-ine" /> <EditText android:inputType="text|textMultiLine" android:minLines="3" android:gravity="top"

android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Date" /> <EditText android:inputType="date" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Signed Decimal Number" /> <EditText android:inputType="number|numberSigned|numberDecimal" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> S dng Gallery, ImageView trong Android Trong Android, chng ti c th hin th nhiu hnh nh trong ch xem nh. Di y l mt v d th vin Android s gii thch lm th no hin th cc hnh nh trong th vin xem. By gi chng ta s thy mt v d th vin n gin v cch s dng b su tp nh mt album nh nh trong hnh ca demo sau. l, khi chng ta click vo mc trong th vin, cc hnh nh tng ng s hin th bn di trong kch thc y bng cch s dng imageview.

To mt file attrs.xml res/values th mc. Tp tin ny c s dng khai bo kiu. Main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/examplegallery" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> Code cho GalleryExample.java : public class GalleryExample extends Activity {

private Gallery gallery; private ImageView imgView; private Integer[] Imgid = { R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5, R.drawable.a_6, R.drawable.a_7 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imgView = (ImageView) findViewById(R.id.ImageView01); imgView.setImageResource(Imgid[0]); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { imgView.setImageResource(Imgid[position]); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId( R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() {

return Imgid.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); imgView.setLayoutParams(new Gallery.LayoutParams(80, 70)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }

SVN : https://kythuatlaptrinh.googlecode.com/svn/trunk/mobile/android/GalleryImagevie w Cc kiu Dialog trong Android Hp thoi Android vi chn Option Trong Android, bng cch s dng hp thoi chng ta c th chn mt ty chn t nhiu ty chn bng cch s dng nt radio.

Code v d cho dialog ny nh sau : public class ExampleApp extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final String items[] = {"item1","item2","item3"}; AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setTitle("Title"); ab.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) { // onClick Action } }) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on Ok button action } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on cancel button action } }); ab.show(); } } Hp thoi Android vi HTML Trong Android, chng ta c th s dng mt s th HTML cho vn bn. Bng cch s dng HTML tag chng ti c th lm cho mt vn bn nh in m v chng ta c th thay i mu sc, vv. y ti s dng '<b>' tag cho t kha '<br>' Bold & cho dng mi trong mt hp thoi cnh bo. chng ta c th s dng m cho vn bn textview, vn bn nt, vv ... public class ExampleApp extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setMessage(Html.fromHtml(" Html View " +" Androidpeople.com")); ab.setPositiveButton("ok", null); ab.show();

} }

Android Progress Dialog Trong Android, chng ti c th hin th thanh tin trnh thng qua hp thoi. i vi iu ny chng ta cn phi s dng ProgressDialog. Di y l mt v d v cch s dng ProgressDialog: public class ExampleApp extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ProgressDialog dialog = ProgressDialog.show(ExampleApp.this, "", "Please wait for few seconds...", true); } }

Android Dialog vi Radio Buttons By gi chng ta c th thy mt v d n gin v cch s dng cc radio groups, actions, and radio trong in thoi di ng Android. V d cho Radio Buttons Android Dialog: public class ExampleApp extends Activity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"}; AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); alt_bld.setIcon(R.drawable.icon); alt_bld.setTitle("Select a Phone Model"); alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = alt_bld.create(); alert.show(); } }

Cho php truy cp cc tnh nng trong Android Nh chng ta bit bt c khi no chng ta s dng mt tnh nng c bit hoc API chng ta cn phi yu cu s cho php trong file AndroidManifest.xml s dng. Nu chng ta khng ch nh bt k truy cp no trong h thng, khi ng

dng s khng s dng cc tnh nng m cn s dng nn trong danh mc c cp php mi c quyn.

Quyn c cp cho ng dng bng cch ci t gi cn ci t. Nhng khng phi tt c cc iu khon s c cp cho h thng. C mt s s cho php h thng m s khng c cp cho cc ng dng ngi dng, nhng ch n cc ng dng h thng. Sau y l mt s trong nhng iu khon khng th c cp cho cc ng dng ngi dng. android.permission.ACCESS_CHECKIN_PROPERTIES android.permission.ACCESS_SURFACE_FLINGER android.permission.ACCOUNT_MANAGER android.permission.BIND_APPWIDGET android.permission.BIND_DEVICE_ADMIN android.permission.BIND_INPUT_METHOD android.permission.BIND_WALLPAPER android.permission.BRICK android.permission.BROADCAST_PACKAGE_REMOVED android.permission.BROADCAST_SMS android.permission.BROADCAST_WAP_PUSH android.permission.CALL_PRIVILEGED android.permission.CHANGE_COMPONENT_ENABLED_STATE

android.permission.CLEAR_APP_USER_DATA android.permission.CONTROL_LOCATION_UPDATES android.permission.DELETE_CACHE_FILES android.permission.DELETE_PACKAGES android.permission.DEVICE_POWER android.permission.DIAGNOSTIC android.permission.FACTORY_TEST android.permission.FORCE_BACK android.permission.GLOBAL_SEARCH android.permission.HARDWARE_TEST android.permission.INJECT_EVENTS android.permission.INSTALL_LOCATION_PROVIDER android.permission.INSTALL_PACKAGES android.permission.INTERNAL_SYSTEM_WINDOW android.permission.MANAGE_APP_TOKENS android.permission.MASTER_CLEAR android.permission.READ_FRAME_BUFFER android.permission.READ_INPUT_STATE android.permission.REBOOT android.permission.SET_ACTIVITY_WATCHER android.permission.SET_ORIENTATION android.permission.SET_PREFERRED_APPLICATIONS android.permission.SET_TIME android.permission.STATUS_BAR android.permission.UPDATE_DEVICE_STATS android.permission.WRITE_GSERVICES android.permission.WRITE_SECURE_SETTINGS c c cc iu khon, ng dng phi c k kt vi phm s dng ng cc nn tng. iu ny c th khc nhau cho cc nh sn xut. V vy, n thc t khng th c c nhng quyn c cp cho mt ng dng ngi dng.

Danh sch cc ng dng Permissions thng gp c s dng bi nh pht trin ng dng Android Google Location-based Services android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION Accessing the Devices Contact Database android.permission.READ_CONTACTS android.permission.WRITE_CONTACTS Accessing Users Calendars android.permission.READ_CALENDAR android.permission.WRITE_CALENDAR Changing Phone Settings android.permission.SET_ORIENTATION android.permission.SET_TIME_ZONE android.permission.SET_WALLPAPER Making, Monitoring Phone Calls android.permission.CALL_PHONE android.permission.CALL_PRIVILEGED Sending and Receiving SMS/MSS messages android.permission.READ_SMS android.permission.RECEIVE_MMS android.permission.RECEIVE_SMS android.permission.RECEIVE_WAP_PUSH android.permission.SEND_SMS android.permission.WRITE_SMS

Edit and Utilize Audio Settings android.permission.RECORD_AUDIO android.permission.MODIFY_AUDIO_SETTINGS Access to Network Settings android.permission.ACCESS_NETWORK_STATE android.permission.CHANGE_NETWORK_STATE Access to Wi-Fi Settings android.permission.ACCESS_WIFI_STATE android.permission.CHANGE_WIFI_STATE Using Internet Network Socket android.permission.INTERNET Access to Phones Hardware android.permission.BLUETOOTH android.permission.CAMERA android.permission.FLASHLIGHT android.permission.VIBRATE android.permission.BATTERY_STATS Manage Google Accounts and Services android.permission.GET_ACCOUNTS android.permission.MANAGE_ACCOUNTS S dng MySpace SDK trong Android Cc Myspace Android SDK cung cp cc chc nng ct li tch hp ti nguyn Myspace vo Android ng dng ca bn Nhng hnh ng sau y c tip xc trc tip thng qua cc SDK : Integrated Login and Logout experience Get and Update Status Mood

Get Friends Upload Photo Upload Video newGet Friends Status Mood newCreate and Get Activities. SDK ny cng i km vi mt mu Myspace Android ng dng chng minh s dng cc hnh ng trn. Trong vi tun ti chng ti s b sung thm cc hnh ng nhiu hn trong SDK, hoc bn c th thc hin bt k API l tip xc thng qua MySpaceID trc tip. Di y l mt vi hnh nh m SDK h tr cho bn, bn cng c th run v d c sn nh km trong SDK. Integrated Login

Get and Set Status Mood

Upload Photo

Get Friends

SVN : http://myspace-android-sdk.googlecode.com/svn/trunk/ Download : http://code.google.com/p/myspace-android-sdk/downloads/list i nt pht trin ng dng Android vi mng x hi Trong phn u ti gii thiu s lc v SDK ca web mng x hi nh MySpace ngoi ra cn nhiu web site khc v mng x hi. Trong source m ti gii thiu v ti chc chn rng bn download v v bung n ra, import vo eclipse.

Trong cc mng x hi hin nay, h u dng chung phng thc chng thc ti khon, thng qua mt nh cung cp th 3.

Nu bn mun pht trin ng dng lm vic vi cc mng x hi, trc tin bn nn ngh s phi to mt app trn mang x hi . Khi n s cp (Consumer key, Consumer secret) v nhng thng s ny l cha kha m ca trc khi bo vo phng.

Ty theo web x hi d hay kh, tc l cc thc web cung cp ng k, i vi Twitter tng i n gin hn Facebook mt cht.

Trong cc hnh trn ti cho cc bn thy cc ng k Application cho cac web x hi nh th no? v h cung cp cho mnh nhng g? Consumer Key, Consumer Secret l nhng ch s c s dng cho OAuth Lm th no login MySpace trong Adnroid? Get source t SVN : http://myspace-androidsdk.googlecode.com/svn/trunk/myspace-android-sample/, Sau khi hon tt v import vo Eclipse phi m bo rng tt c y nh hnh sau,

Nhp key ng k m MySpace cung cp cho bn (ng k y) vo MainActivity theo mi tn nh hnh pha bn trn. Nu bn lm ng theo trnh t kt qu s c sau khi run vi Android.

Click login button, khi y bn s thy mn hnh sau :

Sau khi ng nhp thnh cng, bn s thy nh sau :

By gi bn c th lm vic trn MySpace trn Android. Tm hiu v Intents v Intent Filters trong Android Ba trong s cc thnh phn ct li ca mt ng dng - activity, service v receivers broadcast - c kch hot thng qua tin nhn, intents call. Intent message l mt c s cho run-time rng buc gia cc thnh phn trong cc ng dng ging v khc nhau. Mc ch chnh mt i tng Intent, l mt cu trc d

liu th ng t chc m t tru tng ca hot ng c thc hin - hoc, thng trong trng hp cc broadcasts, m t v mt iu g xy ra v ang c cng b. C nhng c ch ring cho vic cung cp intents cho tng loi component:

Mt i tng Intent c thng qua n Context.startActivity() hoc Activity.startActivityForResult() khi ng mt activity hoc c mt activity hin ti thc hin iu g mi. (N cng c th c truyn cho Activity.setResult() tr v thng tin cho hot ng ny c gi l startActivityForResult().) Mt i tng Intent c thng qua vi Context.startService() bt u mt service hoc cung cp ch dn mi vi mt dch v ang din ra. Tng t nh vy, intent c th c thng qua cho Context.bindService() cho thit lp kt ni gia cc component gi in thoi v service mt mc tiu. N ty chn c th bt u cc service nu n cha c chy. Cc i tng Intent truyn cho bt k method broadcast (nh Context.sendBroadcast(), Context.sendOrderedBroadcast(), hoc Context.sendStickyBroadcast()) u gi n tt c cc receivers broadcast quan tm n. Rt nhiu loi broadcast trong m ngun h thng.

Trong mi trng hp, h thng Android tm thy dch v activity, thch hp, hoc thit lp cc receivers broadcast cho p ng mc ch, instantiating chng nu cn thit. Khng c s chng cho trong cc h thng nhn tin: intents Broadcast c phn phi duy nht cho broadcast receivers , khng bao gi cho activity, service. Mt intent thng qua vi startActivity() c phn phi duy nht cho activity c, khng bao gi cho mt service hoc receiver broadcast, vv.

i tng Intent Mt i tng Intent l mt gi thng tin. N cha thng tin c ch cho cc component tip nhn intent (chng hn nh cc hnh ng c thc hin v cc d liu vi hot ng trn) cng vi cc thng tin quan tm n h thng Android (nh cc chng loi thnh phn nn x l cc intent v hng dn lm th no vi khi ng mt activity mc tiu). V c bn, n th cha nhng iu sau y: Component name Tn ca cc component qun l cc intent. Trng ny l mt i tng ComponentName Tn component l ty chn. Nu n c thit lp, cc i tng Intent l cung cp cho mt instance ca lp c ch nh. Nu n khng c thit lp, Android s dng cc thng tin khc trong i tng Intent vi xc nh mt mc tiu ph hp. Tn component l thit lp bi setComponent(), setClass(), hoc setClassName() v c bi getComponent(). Action Chui t tn cho cc action c thc thi - hoc, trong trng hp intents broadcast, cc action din ra v c thng bo. Lp Intent xc nh mt s constants action, bao gm c cc:

ACTION_CALL ---- activity ---- khi u mt cuc gi in thoi. ACTION_EDIT ---- activity ---- Hin th d liu cho ngi s dng chnh sa. ACTION_MAIN ---- activity ---- Khi ng activity ban u ca cng vic, khng c d liu u vo v u ra. ACTION_SYNC ---- activity ---- ng b d liu trn mt my ch vi d liu trn thit b di ng. ACTION_BATTERY_LOW ---- receiver broadcast ---- Mt cnh bo pin yu. ACTION_HEADSET_PLUG ---- broadcast receiver ---- Mt tai nghe c cm vo thit b, hoc Unplugged t n. ACTION_SCREEN_ON ---- receiver broadcast ---- mn hnh c bt. ACTION_TIMEZONE_CHANGED ---- receiver broadcast ---- Cc thit lp cho mi thi gian thay i.

You might also like