132
Bài này sẽ hướng dẫn cặn kẽ mọi người cách sử dụng Android trong Eclipse, hi vọng giúp những người mới chập chững bước vào lập trình Android có thêm thông tin và biết cách khai thác IDE của mình hiệu quả hơn. I.Hướng dẫn cài đặt Android với Eclipse: Thực chất anh Giáp đã viết một bài có nội dung tương tự, nhưng do Goolge thay đổi phương thức tải Android SDK nên mình quyết định viết lại, gộp luôn vào topic hướng dẫn sử dụng Eclipse. 1.Download Android SDK: Android SDK thực chất là tập hợp các công cụ và thư viện để phát triển các ứng dụng trên nền tảng hệ điều hành Android. B1: Vào trang http://developer.android.com/sdk/index.html để tải Android SDK Starter. Tùy thuộc vào hệ điều hành mà bạn chọn bản Mac, Linux hay Window. Ở đây mình chọn tải bản cho Window. B2: Giải nén file zip bạn vừa tải về. Chạy SDK Setup.exe. Bạn có thể gặp thông báo lỗi Fetching https://dl-sl... Failed to fetch... Close thông báo này lại. Tiếp theo cửa sổ Choose Packages to Install xuất hiện. Nếu cửa sổ này trống rỗng -> Cancel. -> Quay về cửa sổ Android SDK and AVD manager -> Chọn Setting, đánh dấu vào ô Force https://... -> Chọn Available Packages

Android Viet

Embed Size (px)

DESCRIPTION

Lap trình android bằng tiếng việt

Citation preview

  • Bi ny s hng dn cn k mi ngi cch s dng Android trong Eclipse, hi vng gip nhng ngi mi chp chng bc vo lp trnh Android c thm thng tin v bit cch khai thc IDE ca mnh hiu qu hn.

    I.Hng dn ci t Android vi Eclipse: Thc cht anh Gip vit mt bi c ni dung tng t, nhng do Goolge thay i phng thc ti Android SDK nn mnh quyt nh vit li, gp lun vo topic hng dn s dng Eclipse.

    1.Download Android SDK:

    Android SDK thc cht l tp hp cc cng c v th vin pht trin cc ng dng trn nn tng h iu hnh Android.

    B1: Vo trang http://developer.android.com/sdk/index.html ti Android SDK Starter. Ty thuc vo h iu hnh m bn chn bn Mac, Linux hay Window. y mnh chn ti bn cho Window.

    B2: Gii nn file zip bn va ti v. Chy SDK Setup.exe. Bn c th gp thng bo li Fetching https://dl-sl... Failed to fetch... Close thng bo ny li. Tip theo ca s Choose Packages to Install xut hin. Nu ca s ny trng rng -> Cancel. -> Quay v ca s Android SDK and AVD manager -> Chn Setting, nh du vo Force https://... -> Chn Available Packages

  • B3: nh du cc Packages bn mun ti: Documents chnh l phn Javadoc m t hot ng ca cc phng thc v cc lp (phn ny chc chn khng th thiu ri), Sample l cc on code mu, SDK Platform ng vi cc phin bn h iu hnh (2.2 - API level 8, 2.1 - API level 7,...), v Google API pht trin cc phn mm lin quan n dch v ca Google (nh Google Map nu bn mun lp trnh lin quan n GPS). Cc bn c th ti ht nu thch, cn mun ti u th c th nh du nh mnh (lu USB drivers ch dnh cho ngi s dng Windows v mun pht trin ng dng test bng in thoi tht). -> Install Selected

    -> Install

    -> Ca s Install hin ra -> Ngi ch (>_

  • 2.Tch hp Android SDK vo Eclipse:

    B1: Ti Eclipse nu bn cha c. Mi ngi c th phn vn khng bit ti bn no cho ph hp, nhng theo kin ca mnh th c th dng 1 trong 2 bn sau: Eclipse for Java Developers, hoc Eclipse for Java and Report Developers (mnh dng bn sau).

    B2: Khi chy Eclipse, vo Help -> Install new softwares. Chn Add, g vo Name tn bn mun v Location g vo a ch ti v ADT:

    HTML Code:

    https://dl-ssl.google.com/android/eclipse/

    hoc HTML Code:

    http://dl-ssl.google.com/android/eclipse/

  • nu https khng hot ng. Ngoi ra bn cng c th ti thng ADT v my theo

    link http://dl.google.com/android/ADT-0.9.7.zip (bn mi nht 0.9.7 ng vi

    Android 2.2), chn Archive v browse ti file ny (lu khng gii nn)

    -> OK

    -> Check vo phn di Name (s hin ra dng Developer Tools).

    B3: Next, next, Accept, next,...Finish (nh Install mi chng trnh bnh thng).

  • B4: Eclipse -> Windows -> Preferences -> Android

    Nhn nt Browse v chnh ng dn ti th mc ca Android SDK bn ti lc

    trc.

    -> Apply

    -> OK

  • 3.Android Virtual Device (Emulator):

    AVD l my o cho developer pht trin ng dng. to 1 AVD bn vo

    Windows -> Android SDK and AVD Manager -> Virtual Devices chn New.

    -> Ca s Create new AVD hin ra, bn in thng tin cho AVD bn mun:

    Name: Ty (nhng ch c s dng cc k t "a-z", "A-Z", ".-_", ngha l c

    khong trng cng ko c).

    Target: Chn phin bn h iu hnh bn mun (thng mnh to mt Android

    1.6 v mt Android 2.2 test).

    SD Card: g vo Size SD card o cho AVD, hoc chnh ti file c sn. Nhiu

    AVD c th dng chung 1 Sdcard (ch cn to ln u, cc ln sau chnh ng

    dn ti file ).

    Skin: c th Default (HVGA) hoc chn kch c mn hnh bn mun. Ch cn

    quan tm ti 3 option: HVGA (phn gii 320-480 nh G1, G2, i5700...), QVGA

    (240-320 nh HTC Wildfire...), WVGA854 (480-854 nh Milestone, NexusOne...)

    -> Create AVD.

  • II.Mt s chc nng cn bit khi lp trnh Android vi Eclipse:

    Nhng iu mnh nu ra di y u l c bn, c th cc pro bit ht ri, nhng nh mnh ni, bi ny l dnh cho newbie vi hi vng gia tng kin thc c bn cng gim thi gian tm kim cho cc bn.

    1.Debug cho ng dng Android:

    Nhiu ngi chuyn t J2SE hoc J2ME sang Android s ngc nhin v cu lnh debug kinh in System.out.println() khng cn in ra trn ca s Console na.

  • Google thay th n bng Logcat, mt ca s ghi li ton b hot ng ca h iu hnh. m Logcat, trc tin cc bn chn Window -> Open Perspective -> Debug. Nu ko thy option Debug th chn Other v tm Debug trong ca s mi hin ra. Sau chn tab Debug mi xut hin gc trn bn phi ca Eclipse (xem hnh). Theo kinh nghim ca mnh th tt nht l Maximize Logcat ra lun cho d quan st.

    Cm nhn ngy xa khi mi s dng Logcat l ri v kh dng. Nhng cng v sau mnh cng quen v thy n tin hn Console nhiu, v Console ch a ra thng bo do chng ta gi, cn Logcat th a c lun nhng thng bo ca h iu hnh, gip chng ta nm c h iu hnh ang lm g, gi n ci g, khi chy nhng g...

  • 2.File Explorer ca Android:

    File Explorer l mt chc nng hu ch Google a vo gip chng ta qun l file trong sd card v c file system data (ch qun l c ca emulator, khng th truy nhp system data ca thit b tht). FE gip bn d dng a file vo / ly file ra trong sdcard o ca emulator, xa c s d liu ca chng trnh khi to li (only emulator)...

    M FE bng cch vo Window -> Show View -> Others -> Android -> File Explorer. Mnh FE trong ca s Debug cho tin qun l.

  • Device ca Android:

    Device cng l mt chc nng hu ch na trong Android gip bn qun l thit b o cng nh tht ca mnh. M Device bng cch vo Window -> Show View -> Device hoc vo Window -> Show View -> Others -> Android -> Device.

    Chc nng mnh thng s dng nht ca device l Screen Capture, cc k tin ly nh minh ha lm thuyt trnh hoc gii thiu trn Google Market.

  • III.Mt s th thut trong Android v Eclipse:

    1.Hin th ting Vit:

    Window -> Preferences -> General -> Workspace.

    Trong Workspace phn Text File Encoding chn Other -> UTF-8.

    2.T ng s code:

    T hp phm kinh in Ctrl + Space (iu k l l kh nhiu ngi khng bit).

    3.Comment:

    Ctrl + "/": t ng thm cm "//" vo u dng (ko tin lm). Ctrl + Shift + "/": t ng thm "/* */" vo cm c bi en. Ctrl + Shift + "\": t ng b "/* */" vo cm c bi en.

    4.Override:

    i lc bn mun Override phng thc ca mt lp c sn, ko l chng ta s i tm tn phng thc trn mng v g ng li nh th? Nhiu bn gp li khi nh vit li phng thc ny v debug mi ko ra (v n ko phi l li): M:

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    }

    n gin v g thiu ch s.

    Eclipse cung cp phng tin gip ta ghi phng thc ca lp cha vi Source -> Override/Implement Method, nhng cc k nhiu ngi khng bit.

  • Hng dn lp trnh c bn vi Android - Bi 1

    Yu cu kin thc cho lp trnh Android:

    lp trnh android, mnh ngh mi ngi ch cn kin thc java cn bn l hon

    ton ok. Cn bn y c ngha l hiu c th no l class, package, bit

    ngha ca cc t kha nh public, private, protected,... thnh tho cc lnh c

    bn nh if, for(), switch(), while(), ... bit sd cc lnh nh Integer.parseInt() hay

    String.valueOf()... Nn c thm kin thc v gi java.util v y l gi h tr nhiu

    lp rt mnh c s dng trn mi nn, ngoi ra cc gi nh java.io, java.net...

    cng c recommended

    Cc kin thc v cc gi lp trnh cho desktop nh java.awt, java.swing hon ton

    khng cn thit (bn thn mnh cng cha sd ci ny bao gi, nhy vo hc java l

    hc J2ME lun), hay cc gi ca J2ME cng vy Lp trnh Android tuy cng l lp

    trnh di ng, nhng cc in thoi s dng hh Android c cu hnh rt mnh

    (Nexus One c VXL ln ti 1Ghz), v vy 2 nn tng Android v J2ME cng rt khc

    nhau. Android c nhng gi ring h tr lp trnh cho n v khng yu cu kht

    khe v vic ti u code nh J2ME. Tht ng tic v J2ME mnh hc ko ng dng

    c my vo lp trnh Android (tuy nhin 1 s k thut c bn cho lp trnh

    game 2D nh Sprite, double buffering, Tile... th vn ko h ph phm cht no )

    Ci t Android lp trnh:

    lp trnh Android th mi b SDK ca Google l khng , bn cn cn tch hp

    n vo mt IDE nh Eclipse. Anh Gip c 2 bi hng dn rt chi tit v ci t

    Android trong Eclipse cng nh Netbeans, nhng theo mnh mi ngi nn s

    dng Eclipse hn v n c nhiu tnh nng h tr lp trnh Google, cn Netbeans

    th plugin cho Android vn cha hon thin

    Eclipse

    Netbeans

    Tin th mnh ni lun, mnh hc Android theo 2 cun Professional Android

    Application Development v Unlocking Android. C 2 cun u dnh cho beginner

    nhng cun u code nhiu, gii thch t, cun th 2 gii thch r rng hn. Nu

  • c ai c nh tham kho th nn c cun UA trc hiu r hn Android, s

    dng cun PAAD trong vic tham kho cc on code cho lp trnh.

    Understanding Android Application:

    Vic hiu c cc thnh phn (component) to nn mt ng dng Android l rt cn thit cho vic lp trnh. Cc thnh phn ny c chia lm 6 loi bao gm:

    1.Activity: hiu mt cch n gin th Activity l nn ca 1 ng dng. Khi khi ng 1 ng dng Android no th bao gi cng c 1 main Activity c gi, hin th mn hnh giao din ca ng dng cho php ngi dng tng tc.

    2.Service: thnh phn chy n trong Android. Service s dng update d liu, a ra cc cnh bo (Notification) v khng bao gi hin th cho ngi dng thy.

    3.Content Provider: kho d liu chia s. Content Provider c s dng qun l v chia s d liu gia cc ng dng.

    4.Intent: nn tng truyn ti cc thng bo. Intent c s dng gi cc thng bo i nhm khi to 1 Activity hay Service thc hin cng vic bn mong mun. VD: khi m 1 trang web, bn gi 1 intent i to 1 activity mi hin th trang web .

    5.Broadcast Receiver: thnh phn thu nhn cc Intent bn ngoi gi ti. VD: bn vit 1 chng trnh thay th cho phn gi in mc nh ca Android, khi bn cn 1 BR nhn bit cc Intent l cc cuc gi ti.

    6.Notification: a ra cc cnh bo m khng lm cho cc Activity phi ngng hot ng.

    Activity, Service, Broadcast Receiver v Content Provider mi l nhng thnh phn chnh cu thnh nn ng dng Android, bt buc phi khai bo trong AndroidManifest (tham kho bi 2 c gii thiu y v file ny).

    Understanding Android Application Life Cycle: Android c c ch qun l cc process theo ch u tin. Cc process c priority thp s b Android gii phng m khng h cnh bo nhm m bo ti nguyn. 1.Foreground process: l process ca ng dng hin thi ang c ngi dng tng tc. 2.Visible process: l process ca ng dng m activity ang hin th i vi ngi

  • dng (onPaused() ca activity c gi). 3.Service process: l Service ang running. 4.Background process: l process ca ng dng m cc activity ca n ko hin th vi ngi dng (onStoped() ca activity c gi). 5.Empty process: process khng c bt c 1 thnh phn no active. Theo ch u tin th khi cn ti nguyn, Android s t ng kill process, trc tin l cc empty process.

  • Android Activity Life Cycle:

    Nh mnh gii thiu trn , Actitvity l thnh phn quan trng nht v ng vai tr chnh trong xy dng ng dng Android. H iu hnh Android qun l Activity theo dng stack: khi mt Activity mi c khi to, n s c xp ln u ca stack v tr thnh running activity, cc Activity trc s b tm dng v ch hot ng tr li khi Activity mi c gii phng.

    Activity bao gm 4 state: - active (running): Activity ang hin th trn mn hnh (foreground). - paused: Activity vn hin th (visible) nhng khng th tng tc (lost focus). VD: mt activity mi xut hin hin th giao din ln trn activity c, nhng giao din ny nh hn giao din ca activity c, do ta vn thy c 1 phn giao din ca activity c nhng li khng th tng tc vi n. - stop: Activity b thay th hon ton bi Activity mi s tin n trng thi stop - killed: Khi h thng b thiu b nh, n s gii phng cc tin trnh theo nguyn tc u tin. Cc Activity trng thi stop hoc paused cng c th b gii phng v khi n c hin th li th cc Activity ny phi khi ng li hon ton v phc hi li trng thi trc .

    Biu miu t Activity state

  • Vng i ca Activity: - Entire lifetime: T phng thc onCreate( ) cho ti onDestroy( ) - Visible liftetime: T phng thc onStart( ) cho ti onStop( ) - Foreground lifetime: T phng thc onResume( ) cho ti onPause( )

    Khi xy dng Actitvity cho ng dng cn phi vit li phng thc onCreate( )

  • thc hin qu trnh khi to. Cc phng thc khc c cn vit li hay khng ty vo yu cu lp trnh.

    XML trong Android: Khng ging nh lp trnh java thng thng, lp trnh android ngoi cc lp c vit trong *.java cn s dng XML thit k giao din cho ng dng. Tt nhin bn hon ton c th thit k 1 giao din nh mun m khng cn ti bt c 1 dng XML no, nhng sd XML s n gin cng vic i rt nhiu. ng thi sd XML s gip vic chnh sa ng dng sau ny tr nn d dng.

    V nguyn tc, khi lp trnh ng dng ta thit k giao din bng XML v ci t cc x l khi tng tc vi giao din trong code.

    1 s thnh phn c bn trong Android:

    1.Cc layout: Layout c dng qun l cc thnh phn giao din khc theo 1 trt t nht nh. - FrameLayout: Layout n gin nht, thm cc thnh phn con vo gc trn bn tri ca mn hnh. - LinearLayout: thm cc thnh phn con theo 1 chiu nht nh (ngang hoc dc). y l layout c s dng nhiu nht. - RelativeLayout: thm cc thnh phn con da trn mi quan h vi cc thnh phn khc hoc vi bin ca layout. - TableLayout: thm cc thnh phn con da trn 1 li cc ngang v dc. - AbsoluteLayout: thm cc thnh phn con da theo ta x, y.

    Layout c s dng nhm mc ch thit k giao din cho nhiu phn gii. Thng khi lp trnh nn kt hp nhiu layout vi nhau to ra giao din bn mong mun.

    2.XML unit: hiu c cc thnh phn c bn ca XML cng nh vic s dng XML kt hp vi code, ta s i xy dng th mt chng trnh n gin.

    Yu cu: Xy dng 1 ng dng cho php g 1 ni dung vo ri hin th ra ni dung bn di.

    B1: Khi to 1 project ( y s dng Eclipse minh ha). Vo th File -> New -> Android Project. Nu bn mi lp trnh Android ln u th

  • c l dng Android Project s khng hin ra, khi xung pha cui chn Other ri vo Android -> Android Project.

    B2: in thng tin cho project

  • Project name: Example 1

    Build Target: Chn Android 1.5 (mi nht l 2.1 nhng hin ti bn cha cn quan tm ) Application name: Example 1

    Package name: at.exam

    Create Activity: Example

    => Kch nt Finish.

  • B3: Bn khung Package Explore bn tri i ti th mc res, bn s thy c 3 th mc con:

    - drawable: th mc cha cc hnh nh lm icon hoc ti nguyn cho giao din... - layout: cha cc file xml thit k giao din.

  • - values: cha cc gi tr s dng trong ng dng c bn nh ngha, nh cc dng k t (string), cc mu (color), cc themes...

    B4:Vo th mc layout, chn file main.xml v g on code sau vo thay cho ton b ni dung c sn (Eclipse h tr ko th cho xml nhng theo mnh khng nn s dng): M:

    Trong on XML ny chng ta khai bo mt Linear Layout vi 2 thnh phn con ca n l 1 Edit Text (dng g xu k t) vi 1 Text View (hin th xu k t). Linear Layout c khai bo vi t kha orientation nhm ch ra chiu sp xp ca 2 thnh phn con l chiu dc. Cn vi layout_width, layout_height cc bn c th cho gi tr bng "fill_parent" hoc "wrap_content" thng bo thnh phn ny s c chiu rng (di) ph y thnh phn cha hoc ch va bao ni dung. Trong Edit Text v Text View cc bn c th thy c t kha id, t kha ny cho php khai bo id ca cc thnh phn ly v trong code (s cp sau). Ngoi ra t kha hint trong Edit Text cho php hin ra phn ni dung m khi Edit

  • Text vn cha c k t no. "@string/edit_hint" thng bo ly trong file strings.xml xu c tn l edit_hint. Cn textColor ca Text View th thng bo on k t s c hin th vi mu ly trong file colors.xml, textSize ch ra c ch bng 28 pixel v typeface ch ra kiu ch l monospace

    B5:Vn trong th mc res, vo values v chn file strings.xml. B sung thm dng nh ngha cho edit_hint nh sau: M:

    Hello World, Example!

    Example 1

    Enter the work

    here

    B6:Trong th mc values, to file colors.xml (chut phi vo th mc, chn New -> Android XML File, v lu ch s, khng phi l color.xml). G ni dung cho file nh sau: M:

    #ff3300

    OK, vy l bn to mt mu mi cho dng ch s c hin th trong Text View (ff3300 l m hexa ca mu ). Thc cht bn hon ton c th g thng M:

    android:textColor="#ff3300"

    trong file main.xml m khng cn to mi file colors.xml, nhng mc ch ca

    XML trong Android chnh l h tr nng cp chnh sa d dng. Nu sau ny

    bn mun sa mu ca dng text th ch cn vo colors.xml thay i thay v m

    mm trong main.xml (c th rt di nu giao din phc tp).

    Cc thnh phn trn mi ch l cc phn c bn ca XML. Ngoi ra cc bn c th

  • khai bo thm v Animation, Style v Theme (phc tp hn nhiu nn mnh khng

    gii thiu trong phn c bn ny).

    B7: Vy l chng ta hon thin phn giao din vi XML, gi n vit code x l cc s kin cho cc thnh phn: => vo th mc src (source code ca project) => at.exam => Example.java, g ni dung code sau vo: M:

    package at.exam;

    import android.app.Activity;

    import android.os.Bundle;

    import android.view.KeyEvent;

    import android.view.View;

    import android.view.View.OnKeyListener;

    import android.widget.EditText;

    import android.widget.TextView;

    public class Example extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    //Thit lp giao din ly t file main.xml

    setContentView(R.layout.main);

    //Ly v cc thnh phn trong main.xml thng

    qua id

    final EditText edit = (EditText)

    findViewById(R.id.edit_text);

    final TextView text = (TextView)

    findViewById(R.id.text_view);

    //Thit lp x l cho s kin nhn nt gia ca

    in thoi

    edit.setOnKeyListener(new OnKeyListener() {

    @Override

  • public boolean onKey(View v, int keyCode,

    KeyEvent event) {

    if (event.getAction() ==

    KeyEvent.ACTION_DOWN

    && keyCode ==

    KeyEvent.KEYCODE_DPAD_CENTER) {

    text.setText(edit.getText().toString());

    edit.setText("");

    return true;

    }

    else {

    return false;

    }

    }

    });

    }

    }

  • Do qua mt cht kin thc c bn: Trong Android, cc lp s dng to giao din (Edit Text, Text View...) u l lp con ca lp View. Mt s lp thng xuyn c s dng to giao din: - TextView

    - EditText

    - ListView

    - Spinner

    - CheckBox

    - Button

    - RadioButton

    Ngoi ra bn cn c th to 1 View ring ca mnh bng cch k tha View c sn.

    Cc Listener c s dng bt 1 s kin no . y mnh s dng OnKeyListener dng bt s kin khi nhn 1 phm ca in thoi. Ngoi ra thng s dng OnClickListener bt s kin chm vo 1 View ang hin th trn mn hnh. Mi View u phi set Listener ring x l cho s kin tng tc vi n, v mi loi View cng li c nhng Listener dnh ring cho n (VD: CheckBox c OnCheckChangedListener) y mnh s dng hm dng inner nh ngha x l cho OnKeyListener nn c th mi ngi khng quen lm, nhng n cng nm trong phn c bn ca Java y nh.

    ngh lu thm phn R.id.edit_text. ly hoc truy nhp cc thnh phn ta nh ngha trong XML ta phi s dng R.* nh R.layout.main, R.id.edit_text. Lnh findViewById s tr v 1 View c Id thit lp trong phn XML. Do View l lp cha ca EditText vi TextView nn y ta phi p kiu. Ngoi ra cc string hay color cng c th ly v bng lnh getResource() . Vd: getResource().getColor(R.color.text_color)

    B8: Chy chng trnh. Chn Run => Android Application v ch cho emulator khi ng nh. Ai c 1 Android tht c th kt ni qua USB v th nghim lun. T chnh sa trong code v trong XML hiu thm v lp trnh Android. VD:

    M:

  • edit.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    }

    });

    hoc trong XML thm vo phn Text View M:

    android:textSize="50px"

    xem chng trnh thay i nh th no nh ^_^

  • Understanding Android Application:

    Vic hiu c cc thnh phn (component) to nn mt ng dng Android l rt cn thit cho vic lp trnh. Cc thnh phn ny c chia lm 6 loi bao gm:

    1.Activity: hiu mt cch n gin th Activity l nn ca 1 ng dng. Khi khi ng 1 ng dng Android no th bao gi cng c 1 main Activity c gi, hin th mn hnh giao din ca ng dng cho php ngi dng tng tc.

    2.Service: thnh phn chy n trong Android. Service s dng update d liu, a ra cc cnh bo (Notification) v khng bao gi hin th cho ngi dng thy.

  • 3.Content Provider: kho d liu chia s. Content Provider c s dng qun l v chia s d liu gia cc ng dng.

    4.Intent: nn tng truyn ti cc thng bo. Intent c s dng gi cc thng bo i nhm khi to 1 Activity hay Service thc hin cng vic bn mong mun. VD: khi m 1 trang web, bn gi 1 intent i to 1 activity mi hin th trang web .

    5.Broadcast Receiver: thnh phn thu nhn cc Intent bn ngoi gi ti. VD: bn vit 1 chng trnh thay th cho phn gi in mc nh ca Android, khi bn cn 1 BR nhn bit cc Intent l cc cuc gi ti.

    6.Notification: a ra cc cnh bo m khng lm cho cc Activity phi ngng

    hot ng.

    Activity, Service, Broadcast Receiver v Content Provider mi l nhng thnh

    phn chnh cu thnh nn ng dng Android, bt buc phi khai bo trong

    AndroidManifest (tham kho bi 2 c gii thiu y v file ny).

    Understanding Android Application Life Cycle:

    Android c c ch qun l cc process theo ch u tin. Cc process c priority

    thp s b Android gii phng m khng h cnh bo nhm m bo ti nguyn.

    1.Foreground process: l process ca ng dng hin thi ang c ngi dng

    tng tc.

    2.Visible process: l process ca ng dng m activity ang hin th i vi ngi

    dng (onPaused() ca activity c gi).

    3.Service process: l Service ang running.

    4.Background process: l process ca ng dng m cc activity ca n ko hin th

    vi ngi dng (onStoped() ca activity c gi).

    5.Empty process: process khng c bt c 1 thnh phn no active.

    Theo ch u tin th khi cn ti nguyn, Android s t ng kill process, trc

    tin l cc empty process.

  • Trong bi 1 mnh gii thiu s lc v cc thnh phn c bn ca Android cng nh vic s dng XML lp trnh ng dng Android. Trong bi ny mnh s gii thiu thm v Android Manifest v i su hn v vn lm vic vi View.

    Android Manifest

    Trong khung Package Explorer, pha di th mc res, bn s thy 1 file c tn l AndroidManifest.xml. Mi ng dng u cn c AndroidManifest.xml m t nhng thng tin quan trng ca n cho h thng Android bit. Let's look closer: M:

  • C th nhng cng vic m AndroidManifest.xml thc hin: - t tn cho Java package ca ng dng.

    - M t cc thnh phn (component) ca ng dng: activity, service, broadcast receiver hoc content provider. - Thng bo nhng permission m ng dng cn c truy nhp cc protected API v tng tc vi cc ng dng khc.

    - Thng bo nhng permission m cc ng dng khc cn c tng tc vi ng dng hin thi.

    - Thng bo level thp nht ca Android API m ng dng cn chy. (Android 1.0 l level 1, 1.1 l level 2, 1.5 level 3, 1.6 level 4 v 2.0 l level 5). ...

    Hy xem th file AndroidManifest.xml ca chng trnh TooDo mnh ang xy dng:

    M:

  • Main Activity ca chng trnh Too Do ny l activity TooDo. Ngoi ra mnh cn c 1 Activity khc c tn l WorkEnter cho php nhp vo thi gian v ni dung cng vic. 1 Broadcast Receiver c tn l AlarmReceiver nhn alarm gi ti trong intent.

    Khi alarm c nhn s c m thanh v rung (vibration). Tt c cng vic s c vit trong code, nhng bt buc bn phi khai bo cc thnh phn c trong ng dng vo AndroidManifest nu mun chng trnh hot ng.

    Tng t, set permission truy nhp camera, internet, c contact... cng u phi khai bo trong AM. T kha screenOrientation cho php thit lp giao din khi vo ng dng theo chiu dc (portrait - mc nh) hay ngang (landscape), theme cho php s dng style c sn ca android l full-screen (ko c thanh status bar na).

    Intent filter l b lc dng gii hn cc intent c s dng trong activity hay receiver...

    M:

  • B lc trn ch cho php intent m internet vi ng dn nh ngha sn

    (http://www.google.com/m/products/scan)

    Ok, hi vng mi ngi nm c chc nng c bn cng nh cch s dng

    Android Manifest

    Working with View Trong bi 1 mnh gii thiu qua cch s dng Edit Text v Text View. Thc cht cc View cn li cng c cch s dng tng t, bn s kt hp nhiu View khc nhau cho ra giao din mnh mong mun. y mnh s cp nhiu ti List View (theo kin mnh l View kh s dng nht).

    Yu cu: Xy dng mt chng trnh cho php nhp ni dung cng vic v thi gian ri list ra

    B1: Vn bt u bng cch khi to mt Project mi: File -> New -> Android Project.

    Project name: Example 2

    Build Target: Chn Android 1.5 Application name: Example 2

    Package name: at.exam

    Create Activity: Example

    => Kch nt Finish.

    Giao din ta thit k y c 1 Linear Layout lm thnh phn chnh, cc thnh phn con ca n gm 1 Edit Text (dng nhp ni dung cng vic), 1 Linear Layout (li gm cc thnh phn con nhp gi v pht thc hin cng vic), 1 Button ( thm ni dung cng vic vo List View) v 1 List View dng list cc cng vic bn nhp. T kha lines c dng c nh s dng v nn s dng vi Edit Text thay v dng mi wrap_content v nu sd wrap_content th Edit Text s t gin ra nu dng nhp vo vt gii hn ng bao (lm hng giao din bn thit k). T kha gravity thng bo cc thnh phn con s c sp xp ntn thnh phn

  • cha. y mnh dng "center" ngha l thnh phn con nm trung tm. Hy th thm vo 1 Edit Text: M:

    android:gravity="center"

  • B2: i ti res/main.xml xy dng giao din cho chng trnh:

    M:

  • android:padding="5px"

    />

  • android:gravity="center"

    android:text="@string/button_content"

    />

    Giao din ta thit k y c 1 Linear Layout lm thnh phn chnh, cc thnh

    phn con ca n gm 1 Edit Text (dng nhp ni dung cng vic), 1 Linear

    Layout (li gm cc thnh phn con nhp gi v pht thc hin cng vic), 1

    Button ( thm ni dung cng vic vo List View) v 1 List View dng list cc

    cng vic bn nhp.

    T kha lines c dng c nh s dng v nn s dng vi Edit Text thay v

    dng mi wrap_content v nu sd wrap_content th Edit Text s t gin ra nu

    dng nhp vo vt gii hn ng bao (lm hng giao din bn thit k).

    T kha gravity thng bo cc thnh phn con s c sp xp ntn thnh phn

    cha. y mnh dng "center" ngha l thnh phn con nm trung tm. Hy th

    thm vo 1 Edit Text:

    M:

    android:gravity="center"

    Bn s thy dng ch nhp vo s bt u t gia ca Edit Text ch khng bt u t bn tri nh trc na.

    T kha padding dng cch 1 khong cch cho thnh phn. Nu khng c padding th 2 thnh phn con thuc cng 1 LinearLayout s c xp st nhau, nhng nu 1 thnh phn con s dng padding th s to c khong cch vi

  • thnh phn cn li theo mong mun. Ngoi ra cn c paddingLeft, paddingRight, paddingTop, paddingBottom.

    T kha numeric dng gii hn dng k t nhp vo. y mnh mun ch nhp vo ch s nn dng "integer" T kha maxLength dng gii hn s k t nhp vo. Do Edit Text ny dng nhp gi nn maxLength="2".

    Ok, gi n 1 cht kin thc v cc n v ca dimenson: - px (pixel): im chm trn mn hnh. - in (inch)

    - mm (milimet)

    - pt (point) = 1/72 m

    - dp (density - independent pixel): ci ny hi kh gii thch. Ni chung dp c s dng cho nhiu phn gii, v vi phn gii 160 px/inch th 1 dp = 1 px. - sp: gn ging dp, nn s dng cho text size.

    Ni chung nn s dng dp v sp nh ngha size cho cc thnh phn, v n c t l c nh vi phn gii ca mn hnh. Cn nu bn ch tm xy dng cho 1 phn gii nht nh th dng px cho chnh xc v chc chn.

    B3: Ti values/strings.xml chnh sa nh sau: M:

    Example 2

    Enter the work

    here

    Hour

    Minute

    Add work

    B4: To mi colors.xml trong values vi ni dung: M:

  • #cccccc

    OK, vy l hon thin phn giao din. Cc bn c th cho chy th ngay

    kim tra xem giao din nh mun cha ch khng cn i hon thnh c code

    (Run as -> Android Application).

  • B5: Time to coding. Ti th mc src/Example.java v thay i ni dung file nh sau:

    M:

    package at.exam;

    import java.util.ArrayList;

    import android.app.Activity;

    import android.app.AlertDialog;

    import android.content.DialogInterface;

    import android.os.Bundle;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.ArrayAdapter;

    import android.widget.Button;

    import android.widget.EditText;

    import android.widget.ListView;

    public class Example extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    //To mng cha String ni dung cng vic v

    gi

    final ArrayList arrayWork = new

    ArrayList();

    //Adapter dng kt ni mng vi List View

    final ArrayAdapter arrayAdapter = new

    ArrayAdapter(this,

    android.R.layout.simple_list_item_1,

    arrayWork);

  • //Cc EditText vo ni dung cng vic c

    ly v t XML

    final EditText workEnter = (EditText)

    findViewById(R.id.work_enter);

    final EditText hourEdit = (EditText)

    findViewById(R.id.hour_edit);

    final EditText minuteEdit = (EditText)

    findViewById(R.id.minute_edit);

    //Button khi nhn s thm cng vic vo

    ListView

    final Button button = (Button)

    findViewById(R.id.button);

    //ListView cha danh sch cng vic

    final ListView list = (ListView)

    findViewById(R.id.list);

    //Cn set Adapter cho list bit s ly ni

    dung t mng arrayWork

    list.setAdapter(arrayAdapter);

    //nh ngha Listener x l s kin nhn vo

    button

    OnClickListener add = new OnClickListener() {

    @Override

    public void onClick(View v) {

    //Nu 1 trong 3 Edit Text khng c ni

    dung th hin ln thng bo

    if

    (workEnter.getText().toString().equals("") ||

    hourEdit.getText().toString().equals("") ||

    minuteEdit.getText().toString().equals("")) {

    AlertDialog.Builder builder = new

    AlertDialog.Builder(Example.this);

    builder.setTitle("Info missing");

    builder.setMessage("Please enter

    all information of the work");

  • builder.setPositiveButton("Continue", new

    DialogInterface.OnClickListener() {

    public void

    onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated

    method stub

    }

    });

    builder.show();

    }

    //Ly ni dung cng vic v thi gian

    ra t Edit Text v a vo list

    else {

    String str =

    workEnter.getText().toString() + " - "

    +

    hourEdit.getText().toString() + ":"

    +

    minuteEdit.getText().toString();

    arrayWork.add(0,str);

    arrayAdapter.notifyDataSetChanged();

    workEnter.setText("");

    hourEdit.setText("");

    minuteEdit.setText("");

    }

    }

    };

    //set Listener cho button

    button.setOnClickListener(add);

    }

    }

    Mnh ch thch y v on code cng kh d hiu. Tuy nhin cn lu 2 vn y. - Khi to i tng ArrayAdapter: Cc bn thy i s truyn vo l (this, android.R.layout.simple_list_item_1, arrayWork). This l i s ca lp Context

  • ( y chnh l activity Example). Bn s gp Context trong rt nhiu khi to cc lp v nn hiu Context c ngha g. Mnh xin a ra gii thch ca anh Gip (thank mr giaplv):

    Quote:

    Context thuc android.content (android.content.Context).

    L mt Interface (lp giao tip) cha hu ht thng tin v mi trng ng dng ca android, c ngha l mi thao tc, tng tc vi h iu hnh iu phi qua lp ny. N l mt lp abstract (tru tng) cung cp cho nhng lp khc cc phng thc tng tc vi h thng Android. N cho php truy cp ti cc ngun ti nguyn (resources) c nh ngha v cc lp khc. V d nh n c th khi to v chy cc activities, cc broadcast v cc intents,... Chng ta coi nh Contex l mt lp mc ng dng (Application level- lin quan ti h thng).

    Tm li context gip chng ta d dng truy cp v tng tc ti cc ti nguyn ca h thng, cc thng tin, cc dch v (services), cc thng s cu hnh, database, wallpaper, danh b, cuc gi, kt ni, ch rung (vibrator),...

    ***s d hu ht cc lp c lin quan ti UI (layout, button, textview, imageview, listview,...) u pi super ti Context v bn thn n m nhim vic truy cp resource (R.id, R.layout,....). Nu chng ta khng tham chiu ti Context class th ng nhin khng th dng ti cc resources m chng ta to ra.

    Tip theo l android.R.layout.simple_list_item_1, i ny nh ngha cch th hin

    item ( y l String) trong List View. Cc bn hy ghi nh android.R.* l cc ti

    nguyn (resource) c sn ca Android cho php bn truy cp v s dng. Sau ny

    khi hng dn to custom View cho List View mnh s cp li vn ny.

    Cui cng arrayWork chnh l mng cn c bind ca adapter.

    - AlertDialog l lp cho php a ra 1 hp thoi, thng dng a ra thng tin

    hoc cnh bo n gin. Trong code mnh to 1 builder, to tiu (title) cho n,

    a ra thng bo (message) v cui cng l to 1 positive button (nhng khng

    nh ngha x l khi nhn nt ny, v vy nu bn nhn nt th dialog s ch n

    gin thc hin vic ng li).

    B6: Tin hnh chy th chng trnh. Run as -> Android Application. Enjoy

  • yourself

  • Trong bi ny mnh s hng dn cch to 1 custom ViewGroup, s dng ViewGroup ny vo ListView, v cui cng l to 1 Option Menu. y cng s l bi cui cng mnh vit v lm vic vi View, cc bi sau s chuyn qua Intent v BroadCast Receiver.

    Custom ViewGroup ViewGroup thng thng chng ta hay gp l LinearLayout, Relative Layout. Xy dng custom ViewGroup cho php chng ta to 1 tp cc widget c sp xp theo mun ri a vo s dng.

    Yu cu: Xy dng ng dng dng To Do List: Cho php nhp vo ni dung cng vic v thi gian thc hin cng vic ri a vo list cng vic. Cho php xa cc cng vic khi list.

    B1: Khi to project: File -> New -> Android Project Project name: Example 3

    Build Target: Chn Android 1.5 Application name: Example 3

    Package name: at.exam

    Create Activity: Example

    => Kch nt Finish.

    B2: Xy dng custom view group trong XML. i ti res\layout to 1 file XML mi l list.xml. G ni dung sau vo: M:

  • android:layout_height="wrap_content"

    android:text=""

    android:paddingTop="45px"

    android:paddingRight="10px"

    />

    Custom ViewGroup ca chng ta y kh n gin, l 1 LinearLayout cha 2 thnh phn: 1 CheckBox v 1 LinearLayout khc gm 2 TextView hin th ni dung cng vic v thi gian.

    B3: xong giao din cho custom ViewGroup, chng ta s thit k giao din cho chng trnh trong main.xml. y mnh dng li giao din ca Example 2 trong bi 2. M:

  • />

    B4: To file colors.xml trong res\value: M:

  • #ffffff

    #cccccc

    #cccccc

    work_color l mu ca ni dung cng vic trong list. time_color mu ca thi gian cng vic. hint_color mu ca text hint (dng hng dn) cc EditText.

  • B5: Chnh sa file strings.xml trong res\value: M:

    Example 3

    Enter the work

    here

    Hour

    Minute

    Add work

    B6: Time to coding. i ti src\at.exam to mt class mi l CustomViewGroup vi ni dung sau: M:

    package at.exam;

    import android.content.Context;

    import android.view.LayoutInflater;

    import android.widget.CheckBox;

    import android.widget.LinearLayout;

    import android.widget.TextView;

    public class CustomViewGroup extends LinearLayout {

    public CheckBox cb;

    public TextView workContent;

    public TextView timeContent;

    public CustomViewGroup(Context context) {

    super(context);

  • //S dng LayoutInflater gn giao din trong

    list.xml cho class ny

    LayoutInflater li = (LayoutInflater)

    this.getContext()

    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    li.inflate(R.layout.list, this, true);

    //Ly v cc View qua Id

    cb = (CheckBox) findViewById(R.id.check_work);

    workContent = (TextView)

    findViewById(R.id.work_content);

    timeContent = (TextView)

    findViewById(R.id.time_content);

    }

    }

    on code trn gip ta nh ngha giao din ca custom ViewGroup mi da trn file list.xml. Mi ngi cng c th to giao din bng code, ko cn s dng XML nhng s phc tp hn v mnh cng ko gii thiu y.

    B7: To 1 class Work cng trong at.exam th hin cng vic: M:

    package at.exam;

    public class Work {

    private String workContent;

    private String timeContent;

    private boolean isChecked;

    public Work(String workContent, String timeContent)

    {

    this.workContent = workContent;

    this.timeContent = timeContent;

    isChecked = false;

    }

    public String getContent() {

    return workContent;

    }

  • public String getTime() {

    return timeContent;

    }

    public void setChecked(boolean isChecked) {

    this.isChecked = isChecked;

    }

    public boolean isChecked() {

    return isChecked;

    }

    }

    Code rt n gin nn mnh s khng ch thch na.

    B8: Chng ta to xong custem ViewGroup, by gi chnh l lc s dng. To 1 class mi tn l ListWorkApdapter trong at.exam: M:

    package at.exam;

    import java.util.ArrayList;

    import android.content.Context;

    import android.view.LayoutInflater;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.ArrayAdapter;

    import android.widget.CheckBox;

    import android.widget.CompoundButton;

    import android.widget.TextView;

    import

    android.widget.CompoundButton.OnCheckedChangeListener;

    public class ListWorkAdapter extends

    ArrayAdapter{

    ArrayList array;

    int resource;

    Context context;

  • public ListWorkAdapter(Context context, int

    textViewResourceId,

    ArrayList objects) {

    super(context, textViewResourceId, objects);

    this.context = context;

    resource = textViewResourceId;

    array = objects;

    }

    //Phng thc xc nh View m Adapter hin th,

    y chnh l CustomViewGroup

    //Bt buc phi Override khi k tha t

    ArrayAdapter

    @Override

    public View getView(int position, View convertView,

    ViewGroup parent) {

    View workView = convertView;

    if (workView == null) {

    workView = new

    CustomViewGroup(getContext());

    }

    //Ly v i tng Work hin ti

    final Work work = array.get(position);

    if (work != null) {

    TextView workContent = ((CustomViewGroup)

    workView).workContent;

    TextView timeContent = ((CustomViewGroup)

    workView).timeContent;

    CheckBox checkWork = ((CustomViewGroup)

    workView).cb;

    //Set s kin khi nh du vo checkbox

    trn list

    checkWork.setOnCheckedChangeListener(new

    OnCheckedChangeListener() {

    @Override

  • public void

    onCheckedChanged(CompoundButton buttonView,

    boolean isChecked) {

    work.setChecked(isChecked);

    }

    });

    //Ly v ni dung cho TextView v CheckBox

    da vo i tng Work hin ti

    workContent.setText(work.getContent());

    timeContent.setText(work.getTime());

    checkWork.setChecked(work.isChecked());

    }

    return workView;

    }

    }

    ListWorkAdapter s c s dng thay th cho ArrayAdapter c bind vi

    ListView. Thng thng ArrayAdapter ch cho hin th String bng TextView,

    nhng vi vic k tha v override phng thc getView, ta c th nh ngha li

    hin th cho cc thnh phn ca ListView.

  • B9: Vic cui cng cn lm l vit li Activity. Ti Example.java v chnh sa theo ni dung sau: M:

    package at.exam;

    import java.util.ArrayList;

    import android.app.Activity;

    import android.app.AlertDialog;

    import android.content.DialogInterface;

    import android.os.Bundle;

    import android.view.Menu;

    import android.view.MenuItem;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.ArrayAdapter;

    import android.widget.Button;

    import android.widget.EditText;

    import android.widget.ListView;

    public class Example extends Activity {

    //Cc hng dng cho to Option Menu

    private static final int DELETE_WORK = Menu.FIRST;

    private static final int ABOUT = Menu.FIRST + 2;

    ArrayList array;

    ListWorkAdapter arrayAdapter;

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    array = new ArrayList();

    arrayAdapter = new ListWorkAdapter(this,

  • R.layout.list, array);

    final EditText workEnter = (EditText)

    findViewById(R.id.work_enter);

    final EditText hourEdit = (EditText)

    findViewById(R.id.hour_edit);

    final EditText minuteEdit = (EditText)

    findViewById(R.id.minute_edit);

    final Button button = (Button)

    findViewById(R.id.button);

    //To list view cho danh sch cng vic

    final ListView list = (ListView)

    findViewById(R.id.list);

    list.setAdapter(arrayAdapter);

    OnClickListener add = new OnClickListener() {

    @Override

    public void onClick(View v) {

    if

    (workEnter.getText().toString().equals("") ||

    hourEdit.getText().toString().equals("") ||

    minuteEdit.getText().toString().equals("")) {

    AlertDialog.Builder builder = new

    AlertDialog.Builder(Example.this);

    builder.setTitle("Info missing");

    builder.setMessage("Please enter

    all information of the work");

    builder.setPositiveButton("Continue", new

    DialogInterface.OnClickListener() {

    public void

    onClick(DialogInterface dialog, int which) {

    // TODO Auto-generated

    method stub

    }

    });

  • builder.show();

    }

    else {

    String workContent =

    workEnter.getText().toString();

    String timeContent =

    hourEdit.getText().toString() + ":"

    +

    minuteEdit.getText().toString();

    Work work = new Work(workContent,

    timeContent);

    array.add(0, work);

    arrayAdapter.notifyDataSetChanged();

    workEnter.setText("");

    hourEdit.setText("");

    minuteEdit.setText("");

    }

    }

    };

    button.setOnClickListener(add);

    }

    //To Option Menu

    public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);

    menu.add(0, DELETE_WORK, 0,"Delete"

    ).setIcon(android.R.drawable.ic_delete);

    menu.add(0, ABOUT, 0,"About"

    ).setIcon(android.R.drawable.ic_menu_info_details);

    return true;

    }

    //X l s kin khi cc option trong Option Menu

    c la chn

    public boolean onOptionsItemSelected(MenuItem item)

    {

    switch (item.getItemId()) {

  • case DELETE_WORK: {

    deleteCheckedWork();

    break;

    }

    case ABOUT: {

    AlertDialog.Builder builder = new

    AlertDialog.Builder(this);

    builder.setTitle("VietAndroid");

    builder.setMessage("AUTHOR:" + "\n" + "

    Nguyen Anh Tuan" + "\n" + "SOURCE:" + "\n" + "

    diendan.vietandroid.com");

    builder.setPositiveButton("Close", new

    DialogInterface.OnClickListener() {

    public void onClick(DialogInterface

    dialog, int which) {

    }

    });

    builder.setIcon(android.R.drawable.ic_dialog_info);

    builder.show();

    break;

    }

    }

    return true;

    }

    private void deleteCheckedWork() {

    if (array.size() > 0) {

    for (int i = 0; i < array.size(); i++) {

    if (i > array.size()) {

    break;

    }

    if (array.get(i).isChecked()) {

    array.remove(i);

    arrayAdapter.notifyDataSetChanged();

    continue;

    }

    }

    }

  • }

    }

    OK. Vy l xong. Option Menu l menu n ch hin ra khi bn nhn nt Menu ca

    in thoi. Option Menu rt tin trong vic a ra cc ty chnh, ging nh khi bn

    nhn phm Esc khi ang chi game trn PC vy.

    Cc bn c th lu l thay v s dng ArrayList nh trc mnh thay

    bng ArrayList v trong khi to i tng arrayAdapter th i s th 2

    l R.layout.list thay v android.R.layout.simple_list_item_1, ngha l chng ta

    s dng layout do mnh t to thay v layout Android cung cp sn cho hin th cc

    thnh phn ca ListView.

    Nu chy th, cc bn c th thy khi ta nh du vo checkbox ca 1 thnh phn

    trong list, ri nhn Menu v chn delete th thnh phn s b g b khi danh sch.

  • Trong bi ny mnh s i su ni r v Intent, phn c bn v ng vai tr rt

    quan trng trong lp trnh ng dng Android.

    Khi nim v Intent:

    Theo nh ngha ca Google, Intent l mt miu t v mt hot ng cn c

    thc hin. Cn ni mt cch n gin v d hiu hn, Intent l mt c cu cho

    php truyn thng ip gia cc thnh phn ca 1 ng dng v gia cc ng dng

    vi nhau.

    Cc thuc tnh ca Intent:

    - action: l hnh ng c thc hin, vd : ACTION_VIEW, ACTION_MAIN

    - data: l d liu s c x l trong action, thng c din t l mt Uri

    (Uniform Resource Identifier, tham kho

    http://en.wikipedia.org/wiki/Uniform...rce_Identifier hiu r thm chi tit).

    VD:

    ACTION_VIEW content://contacts/people/1 - Hin th thng tin v ngi vi m

    danh 1

    ACTION_DIAL content://contacts/people/1 - Hin th mn hnh gi n ngi vi

    m danh 1

    ACTION_DIAL tel:123 - Hin th mn hnh gi vi s gi l 123

    Ngoi ra cn c 1 s thuc tnh m ta c th b sung vo Intent:

    - category: b sung thm thng tin cho action ca Intent. VD:

    CATEGORY_LAUNCHER thng bo s thm vo Launcher nh l mt ng dng

  • top-level

    - type: ch r kiu ca data

    - component: ch r thnh phn s nhn v x l intent. Khi thuc tnh ny c

    xc nh th cc thuc tnh khc s tr thnh thuc tnh ph.

    - extras: mang theo i tng Bundle cha cc gi tr b sung.

    VD:

    ACTION_MAIN v CATEGORY_HOME: tr v mn hnh Home ca Android (khi

    bm nt Home ca di ng)

    Phn loi Intent:

    Intent c chia lm 2 loi:

    - Explicit Intents: intent c xc nh thuc tnh component, ngha l ch

    r thnh phn s nhn v x l intent. Thng thng intent dng ny s khng b

    sung thm cc thuc tnh khc nh action, data. Explicit Intent thng c s

    dng khi chy cc activity trong cng 1 ng dng.

    - Implicit Intents: Intent khng ch r component x l, thay vo n b sung

    thng tin trong cc thuc tnh. Khi intent c gi i, h thng s da vo nhng

    thng tin ny quyt nh component no thch hp nht x l n.

    VD:

    ACTION_DIAL tel:123 thng thng s c h thng giao cho activity Phone

    Dialer mc nh ca Android x l.

    Mt s action thng s dng trong Intent:

    ACTION_ANSWER - m Activity x l cuc gi ti, thng l Phone Dialer ca

    Android

    ACTION_CALL - m 1 Phone Dialer (mc nh l PD ca Android) v ngay lp tc

    thc hin cuc gi da vo thng tin trong data URI

    ACTION_DELETE - m Activity cho php xa d liu m a ch ca n cha trong

    data URI

    ACTION_DIAL - m 1 Phone Dialer (mc nh l PD ca Android) v in thng tin

    ly t a ch cha trong data URI

  • ACTION_EDIT - m 1 Activity cho php chnh sa d liu m a ch ly t data

    URI

    ACTION_SEND - m 1 Activity cho php gi d liu ly t data URI, kiu ca d

    liu xc nh trong thuc tnh type

    ACTION_SENDTO - m 1 Activity cho php gi thng ip ti a ch ly t data

    URI

    ACTION_VIEW - action thng dng nht, khi chy activity thch hp hin th

    d liu trong data URI

    ACTION_MAIN - s dng khi chy 1 Activity

    OK, l thuyt nh th l tm n. Gi chng ta s chuyn qua phn thc hnh hiu r cch s dng Intent. Nh nu trn, Intent chia lm 2 loi: explicit intent v implicit intent. Mi loi Intent s c cch ci t v s dng khc nhau.

    Using Explicit Intents

    Yu cu: Xy dng chng trnh gm 2 Activity. Activity1 l Activity chy ban u lc khi ng ng dng, cho php nhp vo 1 gi tr, cho php khi chy Activity2 v gi gi tr ny ti Activity2. Activity2 s nhn v hin th gi tr, ri li gi gi tr ny ti 1 BroadcastReceiver. C ch gi v khi chy Activity s dng thng qua Intent.

    B1: Khi to project: File -> New -> Android Project Project name: Explicit Intent Example

    Build Target: Chn Android 1.5 Application name: Explicit Intent Example

    Package name: at.exam

    Create Activity: Activity1

    => Kch nt Finish.

    B2: To giao din cho Activity1 -> res\layout\main.xml chuyn tn thnh activity1_layout.xml

    M:

  • Layout cho Activity1 bao gm 1 LinearLayout cha 1 TextView, 1 EditText nhp gi tr ( gii hn kiu nhp l number), v 1 RelativeLayout c 1 Button khi chy Activity2. Mnh s dng RelaytiveLayout c th xp Button ny xung pha cui ca giao din.

  • B3: To giao din cho Activity2 -> Chut phi vo folder res\layout -> New -> Android XML File ->G tn l activity2_layout.xml M:

  • Layout ca Activity2 tng t nh Activity1, nhng Button by gi l gi BroadCast Receiver. Ngoi ra mnh dng EditText hin th value nhn c (do n c ci ng bao ngoi p hn TextView ^_^) nn khng cho php nhp gi tr vo EditText ny M:

    android:enabled="false"

    B4:Sa li ni dung ca Activity1.java nh sau: M:

    package at.exam;

    import android.app.Activity;

    import android.content.Intent;

    import android.os.Bundle;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.EditText;

    public class Activity1 extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity1_layout);

  • final EditText editValue = (EditText)

    findViewById(R.id.value_edit);

    final Button sendButton = (Button)

    findViewById(R.id.send_button);

    sendButton.setOnClickListener(new

    OnClickListener() {

    public void onClick(View v) {

    String valueString =

    editValue.getText().toString();

    long value;

    if (valueString != null) {

    value =

    Long.parseLong(valueString);

    }

    else {

    value = 0;

    }

    //To 1 i tng Bundle gi

    i cng Intent

    Bundle sendBundle = new Bundle();

    sendBundle.putLong("value",

    value);

    //To Intent khi chy

    Activity2 v gn sendBundble vo Intent

    Intent i = new

    Intent(Activity1.this, Activity2.class);

    i.putExtras(sendBundle);

    startActivity(i);

    //Gii phng Activity1 khi

    Activity Stack v ta s ko quay li n na

    finish();

    }

    });

    }

    }

  • B5: To mi 1 Class Activity2.java trong package at.exam -> chnh sa ni dung: M:

    package at.exam;

    import android.app.Activity;

    import android.content.Intent;

    import android.os.Bundle;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.EditText;

    public class Activity2 extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity2_layout);

    final EditText receiveValueEdit = (EditText)

    findViewById(R.id.value_receive);

    final Button callReceiverButton = (Button)

    findViewById(R.id.call_button);

    //Ly v Bundle c gi km Intent ri ly ra

    gi tr

    Bundle receiveBundle =

    this.getIntent().getExtras();

    final long receiveValue =

    receiveBundle.getLong("value");

    receiveValueEdit.setText(String.valueOf(receiveValue));

    callReceiverButton.setOnClickListener(new

    OnClickListener() {

    public void onClick(View v) {

    //Khi to 1 Intent gi ti

    BroadCast Receiver

  • //Gn gi tr vo Intent, ln ny

    ko cn Bundle na

    Intent i = new

    Intent(Activity2.this, Receiver.class);

    i.putExtra("new value",

    receiveValue - 10);

    sendBroadcast(i);

    }

    });

    }

    }

  • B6: To BroadCast Receiver nhn Intent m Activity2 gi ti -> To 1 file Receiver.java trong at.exam -> Ni dung: M:

    package at.exam;

    import android.content.BroadcastReceiver;

    import android.content.Context;

    import android.content.Intent;

    import android.widget.Toast;

    public class Receiver extends BroadcastReceiver{

    @Override

    public void onReceive(Context context, Intent

    intent) {

    long value = intent.getLongExtra("new

    value", -10) + 10;

    Toast toast = Toast.makeText(context,

    "Broadcast Receiver catch an Intent"

    + " \n" + "The value is stored in

    the Intent is "

    + String.valueOf(value),

    Toast.LENGTH_LONG);

    toast.show();

    }

    }

    Code khng h kh hiu, v mnh cng add comment. Ch cn lu y l Toast l lp hin th mt thng bo n gin trong 1 khong thi gian c nh, v ko th thay i thi gian ny T_T (why???) ch c th chn gia LENGTH_SHORT vi LENGTH_LONG

    B7: B sung thm thng tin v component mi vo AndroidManifest.xml:

  • M:

  • xong s dng Explicit, gi n lt Implicit Intent. Trc khi i vo v d, hy do qua 1 cht kin thc v Intent Filter v vai tr ca n.

    Intent Filter l g Activity, Service v BroadCast Receiver s dng Intent Filter thng bo cho h thng bit cc dng Implicit Intent m n c th x l. Ni cch khc, Intent Filter l b lc Intent, ch cho nhng Intent c php i qua n.

    Intent Filter m t kh nng ca component nh ngha n. Khi h thng bt c 1 Implicit Intent (ch cha 1 s thng tin chung chung v action, data v category...), n s s dng nhng thng tin trong Intent ny, kim tra i chiu vi Intent Filter ca cc component cc ng dng, sau quyt nh khi chy ng dng no thch hp nht x l Intent bt c. Nu c 2 hay nhiu hn ng dng thch hp, ngi dng s c la chn ng dng mnh mun.

    VD:

    M:

    Trn l 1 Activity vi b lc Intent cho php bt v x l cc Intent gi SMS. Hy lu t kha M:

    andoid:scheme

  • T kha ny cho bit protocol (lut) x l d liu trong URI. Ni 1 cch n

    gin th n l kiu ca d liu. 1 s kiu khc nh http, https, fpt, content...

    Using Implicit Intent: Yu cu: Xy dng chng trnh nhp s v gi. Lu chng trnh ca mnh y ch xy dng n mc khi nhn nt Call ca di ng th s chy ng dng v hin th giao din cho php nhp s. Phn gi dnh cho ai yu thch tm hiu thm ^_^ Phn ny khng h kh nhng y mnh ch mun minh ha Implicit Intent nn s khng a vo.

    B1: Khi to project: File -> New -> Android Project Project name: Implicit Intent Example

    Build Target: Chn Android 1.5 Application name: Implicit Intent Example

    Package name: at.exam

    Create Activity: Example

    => Kch nt Finish.

    B2: y l bc quan trng nht v cng l bc c ngha duy nht trong c project ny, cc bc cn li ch l bc ru ria m mnh thm vo cho ci project n ra hn 1 cht. Bc ny s thm 1 b lc Intent Filter vo cho activity Example ca chng ta bt s kin nhn nt Call ca di ng -> Vo AndroidManifest.xml chnh sa nh sau: M:

  • Thc cht ch l b sung thm dng ch mnh nh du thi ^_^

    B3: Xy dng giao din trong main.xml, bc ny ko quan trng, ch l ru ria cho activity c ci giao din: M:

  • android:id="@+id/button4"

    android:layout_width="80px"

    android:layout_height="80px"

    android:gravity="center"

    android:text="4"

    android:textSize="25px"

    />

  • android:layout_height="80px"

    android:gravity="center"

    android:text="8"

    android:textSize="25px"

    />

  • android:text="Clear"

    android:textSize="25px"

    />

    LinearLayout cha 1 TextView hin th s nhn, 1 TableLayout c cc Button tng ng vi cc s v 1 Button clear cho TextView.

  • B4: Code code code... So tired... Tutorial is really take time. Chnh Example.java: M:

    package at.exam;

    import android.app.Activity;

    import android.os.Bundle;

    import android.view.Menu;

    import android.view.MenuItem;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.Button;

    import android.widget.TextView;

    public class Example extends Activity {

    Button button1, button2, button3;

    Button button4, button5, button6;

    Button button7, button8, button9;

    Button button0, buttonStar, buttonClear;

    TextView numberView;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    numberView = (TextView)

    findViewById(R.id.number_display);

    button1 = (Button) findViewById(R.id.button1);

    button2 = (Button) findViewById(R.id.button2);

    button3 = (Button) findViewById(R.id.button3);

  • button4 = (Button) findViewById(R.id.button4);

    button5 = (Button) findViewById(R.id.button5);

    button6 = (Button) findViewById(R.id.button6);

    button7 = (Button) findViewById(R.id.button7);

    button8 = (Button) findViewById(R.id.button8);

    button9 = (Button) findViewById(R.id.button9);

    button0 = (Button) findViewById(R.id.button0);

    buttonStar = (Button)

    findViewById(R.id.button_star);

    buttonClear = (Button)

    findViewById(R.id.button_clear);

    button1.setOnClickListener(this.appendString("1"));

    button2.setOnClickListener(this.appendString("2"));

    button3.setOnClickListener(this.appendString("3"));

    button4.setOnClickListener(this.appendString("4"));

    button5.setOnClickListener(this.appendString("5"));

    button6.setOnClickListener(this.appendString("6"));

    button7.setOnClickListener(this.appendString("7"));

    button8.setOnClickListener(this.appendString("8"));

    button9.setOnClickListener(this.appendString("9"));

    button0.setOnClickListener(this.appendString("0"));

    buttonStar.setOnClickListener(this.appendString("*"));

    buttonClear = (Button)

    findViewById(R.id.button_clear);

  • buttonClear.setOnClickListener(new

    OnClickListener() {

    public void onClick(View v) {

    numberView.setText("");

    }

    });

    }

    public OnClickListener appendString(final String

    number) {

    return new OnClickListener() {

    public void onClick(View arg0) {

    numberView.append(number);

    }

    };

    }

    public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);

    menu.add(0, Menu.FIRST, 0,"Exit"

    ).setIcon(android.R.drawable.ic_delete);

    return true;

    }

    public boolean onOptionsItemSelected(MenuItem item)

    {

    switch (item.getItemId()) {

    case Menu.FIRST: {

    finish();

    break;

    }

    }

    return false;

    }

    }

    Code qu n gin, mnh cn ko thm comment na. Lu c 1 Option Menu

    ng Activity v cng l ng lun ng dng.

    B5: Time to test... Khi chy project, ri s dng Option Menu ca mnh (bm nt

  • Menu ca Emulator hoc di ng Android) thot khi chng trnh. Ok, sau khi

    chn Exit ta c th chc chn l ng dng c ng hon ton, activity ko cn

    tn ti trong stack ca Emulator/di ng na. Gi nhn nt Call ca Emulator/di

    ng, Tadaaaaaaaaa

  • Android Service

    4 Tutorial trc cc bn c 1 lng kin thc kha kh, tip sau y mnh xin gii thiu 1 khi nim c bn na trong android, l Service

    Service l 1 trong 4 thnh phn chnh trong 1 ng dng Android ( Activity, Service, BroadcastReceiver, ContentProvider) thnh phn ny chy trong hu trng v lm nhng cng vic khng cn ti giao din nh chi nhc, download, x l tnh ton

    Mt Service c th c s dng theo 2 cch:

    - N c th c bt u v c cho php hot ng cho n khi mt ngi no dng n li hoc n t ngt. ch ny, n c bt u bng cch gi Context.startService() v dng bng lnh Context.stopService(). N c th t ngt bng lnh Service.stopSelf() hoc Service.stopSelfResult(). Ch cn mt lnh stopService() ngng Service li cho d lnh startService() c gi ra bao nhiu ln

    - Service c th c vn hnh theo nh c lp trnh vic s dng mt Interface m n nh ngha. Cc ngi dng thit lp mt ng truyn ti i tng Service v s dng ng kt ni thm nhp vo Service. Kt ni ny c thit lp bng cch gi lnh Context.bindService() v c ng li bng cch gi lnh Context.unbindService(). Nhiu ngi dng c th kt ni ti cng mt thit b. Nu Service vn cha c khi chy, lnh bindService() c th ty khi chy n. Hai ch ny th khng tch bit ton b. Bn c th kt ni vi mt Service m n c bt u vi lnh startService(). V d, mt Service nghe nhc ch nn c th c bt u bng cch gi lnh startService() cng

  • vi mt i tng Intent m nh dng c m nhc chi. Ch sau , c th l khi ngi s dng mun kim sot trnh chi nhc hoc bit thm thng tin v bi ht hin ti ang chi, th s c mt Activity to lp mt ng truyn ti Service bng cch gi bindService(). Trong trng hp nh th ny, stopService() s khng thc s ngng Service cho n khi lin kt cui cng c ng li.

    Ging nh mt Activity, mt Service cng c cc phng thc chu k thi gian m bn c th ci t kim sot nhng s thay i trong trng thi ca n. Nhng nhng phng thc ca Service th t hn l ca Activity ch c 3- v chng th c s dng rng ri, khng c bo v. void onCreate()

    void onStart(Intent intent)

    void onDestroy()

    Bng vic thc hin nhng phng thc ny, bn c th gim st 2 vng lp ca chu k thi gian ca mi Service Entire lifetime ca mt Service din ra gia thi gian onCreate() c gi ra v thi gian m onDestroy() tr li. Ging nh mt Activity, mt Service li tit hnh ci t ban u onCreate(), v gii phng tt c cc ti nguyn cn li onDestroy() V d, mt Service pht li nhc c th to ra mt lung v bt u chi nhc onCreate(),v sau lung chi nhc s dng li onCreate(), Active lifetime ca mt Service bt u bng mt lnh ti onStart(). yl phng thc c chuyn giao i tng Intent m c thng qua ti startService() Service m nhc s m i tng Intent quyt nh xem s chi loi nhc no v bt u pht nhc. Khng c callback tng ng no cho thi im Service ngng li khng c phng thc onStop() Cc phng thc onCreate() v onDestroy() c gi cho tt c cc Service d chng c c bt u bng Context.startService() hoc Context.bindService() hay khng. Tuy nhin th, onStart() ch c gi ra i vi cc Service bt u bng startService().

    Nu mt Service cho php nhng Service khc kt ni vi n th s c thm cc phng thc callback dnh cho Service thc hin

    IBinder onBind(Intent intent)

    boolean onUnbind(Intent intent)

    void onRebind(Intent intent)

    Hm callback onBind() thng qua i tng Intent oc truyn n bindService v onUnbind() c chuyn giao i tng m c chuyn n. Nu Service

  • ang c ch nh (binding), onBind() quay tr li knh thng tin m ngi dng s dng tng tc vi Service. Phng thc onUnbind() c th yu cu onRebind() c gi nu mt ngi dng kt ni vi Service

    Biu di y minh ha cho cc phng thc callback ginh cho mt Service. Mc d, n phn tch cc Service c to ra thng qua startService vi cc Service m c to ra bng bindService(). Hy nh rng bt k Service no, cho d n c khi to nh th no th n vn c th cho php cc ngi dng kt ni ti n mt cch hiu qu nht, cho nn bt k Service no cng c th c ch nh thng qua cc cc phng thc onBind()v onUnbind()

    Service LifeCycle

  • Cc bn c v hiu v Service trong Part 1. Tip theo mnh s lm 1 demo nh cc bn hiu r hn v Service. Demo to 1 service chi nhc v ngi s dng c th iu khin service ny.

    Giao din chng trnh :

  • u tin l to 1 giao din iu khin service chi nhc bng layout n gin :

    M:

  • To 1 class LocalService.java extend t Service v mt lp con LocalBinder tha k t lp Binder ( dng iu khin service )

    M:

    public class LocalService extends Service {

    public class LocalBinder extends Binder {

    LocalService getService() {

    return LocalService.this;

    }

    }

    .....

    }

    T np chng phng thc onBind bng cch tr li gi tr mBinder

    M:

    private final IBinder mBinder = new LocalBinder();

    @Override

    public IBinder onBind(Intent intent) {

    return mBinder;

    }

    To mt i tng MediaPlayer chi nhc n gin ( s dng chi file abc.mp3 t trong folder res/raw ):

    M:

    MediaPlayer mMediaPlayer;

    public void startMp3Player() {

    mMediaPlayer =

    MediaPlayer.create(getApplicationContext(),

    R.raw.abc);

    mMediaPlayer.start();

    }

    public void mp3Stop() {

    mMediaPlayer.stop();

    mMediaPlayer.release();

    }

  • lp LocalServiceBinding.java extend t lp Activity chng ta ch cn n i tng mConnection c nhim v gim st kt ni ca service chi nhc. M:

    private ServiceConnection mConnection = new

    ServiceConnection() {

    public void onServiceConnected(ComponentName

    className, IBinder service) {

    mBoundService =

    ((LocalService.LocalBinder)service).getService();

    Toast.makeText(LocalServiceBinding.this,

    R.string.local_service_connected,

    Toast.LENGTH_SHORT).show();

    }

    public void onServiceDisconnected(ComponentName

    className) {

    mBoundService = null;

    Toast.makeText(LocalServiceBinding.this,

    R.string.local_service_disconnected,

    Toast.LENGTH_SHORT).show();

    }

    };

    V x l s kin 3 button ( Bind, Unbin, Play/Stop ) M:

    private OnClickListener mBindListener = new

    OnClickListener() {

    public void onClick(View v) {

    bindService(new

    Intent(LocalServiceBinding.this,

    LocalService.class), mConnection,

    Context.BIND_AUTO_CREATE);

    mIsBound = true;

    mPlayButton.setEnabled(true);

    }

    };

    private OnClickListener mPlayListener = new

    OnClickListener() {

  • public void onClick(View v) {

    if(mPlayButton.getText() == "Play")

    {

    mBoundService.startMp3Player();

    mPlayButton.setText("Stop");

    }

    else

    {

    mBoundService.mp3Stop();

    mPlayButton.setText("Play");

    }

    }

    };

    private OnClickListener mUnbindListener = new

    OnClickListener() {

    public void onClick(View v) {

    if (mIsBound) {

    unbindService(mConnection);

    mIsBound = false;

    mPlayButton.setEnabled(false);

    }

    }

    };

    Hng dn lp trnh c bn vi Android - Bi 6

    Bi 6 : Android SQLite Database

    Trong bi hm nay mnh s gii thiu vi cc bn c s d liu trn Android - SQLiteDatabase.

    0. Gii thiu SQLite Database Mi ng dng u s dng d liu, d liu c th n gin hay i khi l c 1 cu trc. Trong Android th h c s d liu c s dng l SQLite Database, y l h thng m ngun m c s dng rng ri trong cc ng dng ( Mozilla

  • Firefox s dng SQLite lu tr cc d liu v cu hnh, iPhone cng s dng c s d liu l SQLite). Trong Android , c s d liu m bn to cho 1 ng dng th ch ng dng c quyn truy cp v s dng, cc ng dng khc th khng. Khi c to, c s d liu SQLite c cha trong th mc /data/data//databases .

    Tip theo mnh s gii thiu vi cc bn cch to v s dng c s d liu SQLite . Cch tt nht hiu l thuyt l thc hnh, cc bn c th to ngay 1 project trong workspace t tn l : SQLiteDemo. ng dng ny n gin ch to 1 c s d liu USER bao gm 2 trng ( id , name ) , ngoi ra c cc thao tc thm , c , sa , xa.

  • Cc bc thc hin vi CSDL:

    1. To 1 CSDL ( thng thng ch cn lm 1 ln ) 2. M CSDL 3. Thm gi tr vo trong table 4. Truy vn. 5. ng CSDL

    1. To c s d liu. u tin cc bn add 1 class DBAdapter x l tt c cc thao tc lin quan n CSDL.

    M:

    public static final String KEY_ID = "_id";

    public static final String KEY_NAME = "name";

    private DatabaseHelper mDbHelper;

    private SQLiteDatabase mDB;

    private static final String DATABASE_CREATE =

    "create table users (_id integer primary key

    autoincrement, "

    + "name text not null);";

    private static final String DATABASE_NAME =

    "Database_Demo";

    private static final String DATABASE_TABLE =

    "users";

    private static final int DATABASE_VERSION = 2;

    private final Context mContext;

    To 1 lp bn trong DBAdapter c extend t lp SQLiteOpenHelper, override 2 phng thc onCreate() v onUpgrade() qun l vic to CSDL v version ca CSDL .

  • M:

    private static class DatabaseHelper extends

    SQLiteOpenHelper{

    public DatabaseHelper(Context context,

    String name,

    CursorFactory factory, int

    version) {

    super(context, name, factory, version);

    // TODO Auto-generated constructor stub

    }

    @Override

    public void onCreate(SQLiteDatabase db) {

    // TODO Auto-generated method stub

    db.execSQL(DATABASE_CREATE);

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int

    oldVersion, int newVersion) {

    // TODO Auto-generated method stub

    Log.i(TAG, "Upgrading DB");

    db.execSQL("DROP TABLE IF EXISTS

    users");

    onCreate(db);

    }

    }

    2. M CSDL : M:

    public DBAdapter open()

    {

    mDbHelper = new DatabaseHelper(mContext,

    DATABASE_NAME, null, DATABASE_VERSION);

    mDB = mDbHelper.getWritableDatabase();

    return this;

    }

    3. Thm gi tr vo CSDL

  • M:

    public long createUser(String name){

    ContentValues inititalValues = new

    ContentValues();

    inititalValues.put(KEY_NAME, name);

    return mDB.insert(DATABASE_TABLE, null,

    inititalValues);

    }

    4. Truy vn Bn c th get ton b data hoc c th get data theo ID ( tin cho vic chnh sa hay cp nht thng tin ca tng bn ghi). M:

    public Cursor getAllUsers(){

    return mDB.query(DATABASE_TABLE, new

    String[] {KEY_ID, KEY_NAME}, null, null, null, null,

    null);

    }

    Cn rt nhiu cc thao tc nh sa, xa, update.... bn ghi, cc bn c th t pht trin. Tt c cc chc nng u c cung cp bi lp SQLiteDatabase, cc bn ch cn c th ha bng cc cu truy vn l c.

    5. ng CSDL M:

    public void close(){

    mDbHelper.close();

    }

    6. S dng CSDL test CSDL m bn va to, cc bn c th thm 1 vi dng code thm 1 user v hin th CSDL ln mn hnh thng qua lp Activity ban u: y mnh create 1 user thng qua cu lnh mDB.createUser("Username"); sau M:

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

  • setContentView(R.layout.main);

    mDB = new DBAdapter(this);

    mDB.open();

    mDB.createUser("Do Minh Thong");

    getData();

    }

    private void getData(){

    mCursor = mDB.getAllUsers();

    startManagingCursor(mCursor);

    String[] from = new String[]{DBAdapter.KEY_NAME};

    int[] to = new int[] {R.id.text1};

    SimpleCursorAdapter users = new

    SimpleCursorAdapter(this, R.layout.users_row, mCursor,

    from, to);

    setListAdapter(users);

    }

    Kt qu :

  • Sourcecode y : http://www.mediafire.com/?yzw2d1ijymo

    Bi ny l bi c s mnh vit tip Phn 7 : ContentProvider , cc bn ch

    theo di nh

  • Android Content Provider

    Cui tun rnh ri hn, nh ra l phi tip tc vit Tutorial cho din n, rt nhiu cc Newbies ang cn

    Trc khi vo bi, cc bn down Sourcecode ca bi hc ti y Sourcecode ca bi hc bao gm 3 Project demo : ContentProviderDemo

    ContentProviderDemo1

    ContentProviderDemo2

    Mi Demo s gii quyt tng vn ca Tutorial. Cc bn c add ht vo workspace tin theo di.

    1. Gii thiu Content Provider

    Content Provider l 1 trong 4 thnh phn c bn ca 1 ng dng Android thng c bao gm: 1. Activity

    2. Service

    3. Broadcast Receiver

    4. Content Provider

    Mt Content Provider cung cp mt tp chi tit d liu ng dng n cc ng dng khc. Thng c s dng khi chng ta mun to c s d liu di dng public (cc ng dng khc c th truy xut ). D liu thng c lu tr file h thng, hoc trong mt SQLite database. n gin cc bn c th hnh dung nh : Danh b, Call log, cu hnh ci t...trn in thoi l d liu di dng Content Provider.

  • Content Provider hin thc mt tp phng thc chun m cc ng dng khc c th truy xut v lu tr d liu ca loi n iu khin. Tuy nhin, nhng ng dng khng th gi cc phng thc trc tip. Hn th chng dng lp Content Resolver v gi nhng phng thc . Mt Content Resolver c th giao tip n nhiu content provider; n cng tc vi cc provider qun l bt k giao tip bn trong lin quan.

    n gin hn, chng ta c th lm 1 ng dng nh ly tt c cc thng tin cu hnh trong my load ln listview. Cc bn c th chy Project ContentProviderDemo1 trong SourcecodeDemo.

  • Chng ta c th tm hiu s qua v code ca demo ny, rt ngn gn

  • M:

    ContentResolver cr = getContentResolver();

    Cursor cursor =

    cr.query(Settings.System.CONTENT_URI, null, null, null,

    null);

    startManagingCursor(cursor);

    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);

    Nh cc bn thy, ch cn 2 dng code n gin ly c con tr thao tc trn tp d liu cn ly:

    M:

    ContentResolver cr = getContentResolver();

    Cursor cursor =

    cr.query(Settings.System.CONTENT_URI, null, null, null,

    null);

    Lp Content Resolver cung cp cc phng thc x l d liu thng qua cc Uri, mi Content Provider c 1 Uri c th , y Uri Settings.System.CONTENT_URI s tr li tp d liu l thng tin cu hnh ca thit b. Sau khi ly c con tr ti tp d liu, vic cn li n gin l bind data ln listview hin th:

  • M:

    startManagingCursor(cursor);

    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)

  • 2. To v s dng 1 Content Provider do ngi dng t nh ngha

    d hiu hn cc bn m Project ContentProviderDemo trong Sourcecode down v. Trong Project mnh to 1 Content Provider Books, mi bn ghi Book bao gm 2 trng : ID v Title.

    Sau y l cc bc to 1 Content Provider c bn ( c th l to

    ContentProvider Book)

    1. To 1 class tha k lp ContentProvider

    M:

    public class BookProvider extends ContentProvider

    2. nh ngha 1 bin Uri (public static final ) c gi CONTENT_URI. Cc xu ny lun c bt u bng content:// tip theo l ni dung ca m ContentProvider x l. Xu ny phi c c tnh l duy nht. M:

    public static final String PROVIDER_NAME =

    "com.vietandroid.provider.Books";

    public static final Uri CONTENT_URI =

    Uri.parse("content://" + PROVIDER_NAME + "/books");

    3. Khai bo cc xu nh ngha cho tng thuc tnh tng ng vi cc ct gi tr t Cursor. M:

    public static final String _ID = "_id";

    public static final String TITLE = "title";

    4. Chng ta cn to h thng cha d liu cho ContentProvider, c th cha di nhiu hnh thc : s dng XML, thng qua CSDL SQLite, hay thm ch l WebService. Trong Demo ny chng ta s dng cch ph bin nht l SQLite:

  • M:

    private SQLiteDatabase bookDB;

    private static final String DATABASE_NAME =

    "Books";

    private static final String DATABASE_TABLE =

    "titles";

    private static final int DATABASE_VERSION = 1;

    5. nh ngha tn ca cc ct m chng ta s tr li gi tr cho cc clients.Nu chng ta ang s dng Database ContentProvider hay cc lp SQLiteOpenHelper, tn cc ct ny chnh l id ca cc ct trong c s d liu SQL. Trong trng hp ny, chng ta phi gp c ct c gi tr l s nguyn c gi _id nh ngha id ca mi bn ghi.

    Nu ang s dng c s d liu SQLite, n s l INTEGER PRIMARY KEY AUTOINCREMENT. Ty chn AUTOINCREMENT khng bt buc, c tc dng t ng tng ID ca mi bn ghi ln nu ngi dng khng nhp. Android cung cp SQLiteOpenHelper gip to v qun l cc phin bn ca c s d liu.

    M:

    private static final String DATABASE_CREATE =

    "create table " + DATABASE_TABLE +

    " (_id integer primary key autoincrement, "

    + "title text not null);";

    private static class DatabaseHelper extends

    SQLiteOpenHelper

    {

    public DatabaseHelper(Context context) {

    super(context, DATABASE_NAME , null,

    DATABASE_VERSION);

    }

    @Override

    public void onCreate(SQLiteDatabase db) {

    db.execSQL(DATABASE_CREATE);

  • }

    @Override

    public void onUpgrade(SQLiteDatabase db, int

    oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS

    titles");

    onCreate(db);

    }

    }

    6. Nu chng ta mun public cc d liu kiu byte nh bitmap th cc trng m cha d liu ny nn l mt xu vi 1 content://URI cho file . y chnh l lin kt cc ng dng khc c th truy cp v s dng d liu bitmap ny.

    7. S dng Cursor thao tc trn tp d liu : query (), update(), insert(), delete().. C th gi phng thc ContentResolver.notifyChange() bitkhi no d liu c cp nht.

    Add Book

    M:

    @Override

    public Uri insert(Uri uri, ContentValues values) {

    long rowID = bookDB.insert(DATABASE_TABLE,

    "", values);

    if(rowID > 0)

    {

    Uri mUri =

    ContentUris.withAppendedId(CONTENT_URI, rowID);

    getContext().getContentResolver().notifyChange(mUr

    i, null);

    return mUri;

    }

    throw new SQLException("Failed to insert new

    row into " + uri);

    }

  • Get All Books

    M:

    @Override

    public Cursor query(Uri uri, String[] projection,

    String selection,

    String[] selectionArgs, String

    sortOrder) {

    SQLiteQueryBuilder sqlBuilder = new

    SQLiteQueryBuilder();

    sqlBuilder.setTables(DATABASE_TABLE);

    if(uriMatcher.match(uri) == BOOK_ID)

    sqlBuilder.appendWhere(_ID + "=" +

    uri.getPathSegments().get(1));

    if(sortOrder == null || sortOrder == "")

    sortOrder = TITLE;

    Cursor c = sqlBuilder.query(bookDB,

    projection, selection, selectionArgs, null, null,

    sortOrder);

    c.setNotificationUri(getContext().getContentResolv

    er(), uri);

    return c;

    }

    }

    Mnh ch demo 2 chc nng l thm sch v ly ton b bn ghi trong CSDL , ngoi ra cc phng thc edit, sa , update, xa... cc bn c th t lm .

  • 8. Khai bo Content Provider trong file AndroidManifest.xml M:

    Nh vy chng ta to xong ContentProvider Book t nh ngha.

  • 9. Test th thnh qu : Mi content Provider gn vi 1 Uri c th, nh trn th ContentProvider Book c Uri l: M:

    com.vietandroid.provider.Books/books

    test th , vn trong Project Demo ContentProviderDemo , cc bn c th thm 2 Button Add Book v View All Books vo . Giao din nh sau:

  • Chng ta s thm 1 Book vo CSDL thng qua URI ny: M:

    public void addBook(String title)

    {

    ContentValues values = new ContentValues();

    values.put(BookProvider.TITLE, title);

    Uri uriInsert =

    getContentResolver().insert(BookProvider.CONTENT_URI,

    values);

    if(uriInsert != null)

    {

    Toast.makeText(this, "Book's added",

    Toast.LENGTH_SHORT).show();

    }

    Log.d(getClass().getSimpleName(),uriInsert.toStrin

    g());

    }

    Kt qu :

  • Truy vn ton b d liu Books c trong CSDL M:

    public void getAllBooks()

    {

    Uri uriGetListTitles =

    Uri.parse("content://com.vietandroid.provider.Books/boo

    ks");

    Cursor c = managedQuery(uriGetListTitles, null,

    null, null, "title desc");

    if(c.moveToFirst()){

    do{

    String bookRecord = "ID = " +

    c.getString(c.getColumnIndex(BookProvider._ID)) + "

    Title = " +

    c.getString(c.getColumnIndex(BookProvider.TITLE));

  • Toast.makeText(this, bookRecord ,

    Toast.LENGTH_LONG).show();

    }while(c.moveToNext());

    }

    }

    Kt qu : [IMGhttp://i123.photobucket.com/albums/o286/firewall7845/VietAndroid/2-

    1.png[/IMG]

    3. S dng d liu Content Provider t 1 ng dng bt k Bi 6 mnh cp v c s d liu SQLite Database, dng d liu ny khng public cho cc ng dng khc s dng, d liu ca ng dng no th ng dng s dng. 1 li th ca d liu di dng Content Provider l public, tt c cc ng dng u c th truy cp v s dng.

    Phn ny cc bn s dng ProjectDemo l ContentProviderDemo2 trong sourcecode i km ban u. Demo ny ch n gin l c li ton b d liu trong CSDL Books c to trong phn 2. Nh mnh ni trn, ch cn ly c Uri ca ContentProvider cn ly v cc tn ca cc trng d liu th chng ta c th truy vn c ht. Trong hm onCreate() cc bn thm vo: M:

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Uri uriGetListTitles =

    Uri.parse("content://com.vietandroid.provider.Books/boo

    ks");

    Cursor c = managedQuery(uriGetListTitles, null,

    null, null, "title desc");

    if(c != null)

    {

    if(c.moveToFirst()){

    do{

  • String bookRecord = "ID = " +

    c.getString(c.getColumnIndex("_id")) + " Title = " +

    c.getString(c.getColumnIndex("title"));

    Toast.makeText(this, bookRecord ,

    Toast.LENGTH_LONG).show();

    }while(c.moveToNext());

    }

    }

    else {

    Toast.makeText(this, "Database is emtpy",

    Toast.LENGTH_SHORT).show();

    }

    }

    2 trng d liu y c nh ngha trn l "_id" v "title". Phn truy vn vn nh vy. Kt qu :

  • Trong bi ny mnh s trnh by tm tt nhng kin thc c bn nht v Intent trong lp trnh Android, cch truyn nhn thng tin qua Intent v minh ha bng mt v d n gin. Hy vng s gip cc bn mi lm quen vi Android nm bt c mt cch nhanh chng.

    I- Intent l g?

    -L mt cu trc d liu m t cch thc, i tng thc hin ca mt Activity -L cu ni gia cc Activity : ng dng Android thng bao gm nhiu Activity, mi Activity hot ng c lp vi nhau v thc hin nhng cng vic khc nhau.

    Intent chnh l ngi a th, gip chng ta triu gi cng nh truyn cc d liu cn thit thc hin mt Activity t mt Activity khc. iu ny cng ging nh vic di chuyn qua li gia cc Forms trong lp trnh Windows Form

    (Ch : trong hnh v trn Activity B ch tr v kt qu khi cn thit. VD : gi s Activity A nhc ngi dng chn nh profile ; Activity B lit k cc nh trong sdcard v cho php ngi dng chn nh. Khi cp code+result l cn thit v c th l 0:null tc cancel hoc 1:nh 20 tc chn nh 20)

    bit thm v Activity xem ti y.

  • -Intent l mt khi nim then cht v c trng ca Android Platform. C th ni lp trnh Android chnh l lp trnh intent-base.

    II-Intent cha nhng d liu g ?

    -Intent v c bn l mt cu trc d liu, c m t trong lp android.content.Intent

    -Cc thuc tnh ca mt i tng Intent :

    -Cc action nh ngha sn :

  • y l nhng hng String c nh ngha sn trong lp Intent. i km vi n l cc Activity hay Application c xy dng sn s c triu gi mi khi Intent tng ng c gi (tt nhin khi c cung cp ng data). VD: +Dial mt s phone:

    PHP Code:

    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.

    parse("tel:123456"));

    startActivity(dialIntent);

    +Hin danh b in thoi:

  • PHP Code:

    Intent listContacts = new Intent(Intent.ACTION_VIEW,

    Uri.pa

    rse(content://contacts/people/);

    startActivity(listContacts);

    n y chc bn s t hi nhng chui data trong hm Uri.parse(data) c ngha l g? l nh dng d liu tng ng vi mi action (chun RFC 3986). Mt khi bn s dng built-in action th bn phi cung cp data cho n theo nh dng ny. Bng di y lit k mt s nh dng v action tng ng c nh ngha sn:

    -T nh ngha action

    V nguyn tc bn c th t tn action ca mt intent l bt c th g theo chun t tn thng thng, hay thm ch dng lun hng action nh ngha sn nh ACTION_VIEW (hay android.intent.action.VIEW). Ci tn VIEW thc cht ch l mt tn gi t, bn c th dng n vi mc ch thc hin mt activity gi mail! Tuy nhin iu r rng l rt ng ngn. Thay vo ta hy

  • dng ACTION_SEND hay ACTION_SENDTO.

    Vic t tn action cho intent ng tn gi t cn c mt ngha khc l app ca bn c th c triu gi t mt app khc. V d bn vit mt app c activity p ng intent ACTION_SEND v chia s mt bc nh ln trang web ca bn (ging nh ta lm vi Facebook, Flickr etc.) Khi c th app ca bn s l mt la chn chia s nh ca ngi dng in thoi.

  • III-S dng Intent nh th no?

    -Cc hm thc thi Activity

    -Intent tng minh thc thi Activity

    Nh trnh by phn II, intent c th dng thuc tnh ph component ch nh ch danh tn lp s thc thi Activity. thc hin iu ny, lp Intent cung cp cc hm l setComponent(C