Professional Documents
Culture Documents
Lap Trinh Di Dong Voi J2ME - 252528khoa CNTT DHKHTN-252529
Lap Trinh Di Dong Voi J2ME - 252528khoa CNTT DHKHTN-252529
04/2005
Mc lc
Trang Mc lc ..................................................................................................................................... 2 I.
1. 2. a) b) 3. a) 4. a) b) c) 5.
II.
1. 2. a) b) c) d) e) f) g) 3. a) b) c) d)
III.
1. 2. a)
b) c) d) e) f) g) h) 3. a) b) c) d) e) f) g) h) i) 4.
To mt i tng Canvas...........................................................................................................................................34 V trn i tng Canvas ............................................................................................................................................35 S kin hnh ng .......................................................................................................................................................35 M phm.......................................................................................................................................................................36 Cc hnh ng trong x l cc tr chi .......................................................................................................................36 Xc nh cc hnh ng ca tr chi...........................................................................................................................37 S kin con tr.............................................................................................................................................................40 Lp Graphics ..................................................................................................................................................................42 H tr mu...................................................................................................................................................................42 Loi nt v ...................................................................................................................................................................43 V cung........................................................................................................................................................................43 V hnh ch nht..........................................................................................................................................................46 Font ch.......................................................................................................................................................................46 im neo .....................................................................................................................................................................47 V cc chui k t .......................................................................................................................................................48 V nh..........................................................................................................................................................................54 Mt s cc phng thc khc ca lp Graphics ..........................................................................................................57 Cc hm API dng lp trnh Game .........................................................................................................................58
IV.
1. 2. 3.
X l s kin ............................................................................................................... 59
i tng Command......................................................................................................................................................59 i tng Item................................................................................................................................................................60 V d ................................................................................................................................................................................60
V.
1. 2. a) b) c) 3. 4. 5. 6. 7. 8.
VI.
1.
2. a) b) 3.
H tr giao thc HTTP trong MIDP ..........................................................................................................................113 Request and response protocols .................................................................................................................................114 The HttpConnection API ...........................................................................................................................................116 Accessing a Java servlet ...............................................................................................................................................122
Ph luc................................................................................................................................................................................... 127
2. L do chn J2ME a) Java ban u c thit k dnh cho cc my vi ti nguyn b nh hn ch. b) Th trng ca J2ME c m rng ra cho nhiu chng loi thit b nh: Cc lai th c nhn nh Java Card My in thoi di ng My PDA (Personal Digital Assistant - thit b tr gip c nhn) Cc hp iu khin dnh cho tivi, thit b gii tr gia dng
3. Kin trc ca J2ME Phn ny s trnh by kin trc tng qut ca nn tng Java
Trang: 5
a) Gii thiu cc thnh phn trong nn tng J2ME: nh ngha v Configuration (Cu hnh): l c t nh ngha mt mi trng phn mm cho mt dng cc thit b c phn loi bi tp hp cc c tnh, v d nh: Kiu v s lng b nh Kiu v tc b vi x l Kiu mng kt ni Do y l c t nn cc nh sn xut thit b nh Samsung, Nokia bt buc phi thc thi y cc c t do Sun qui nh cc lp trnh vin c th da vo mi trng lp trnh nht qun v thng qua s nht qun ny, cc ng dng c to ra c th mang tnh c lp thit b cao nht c th. V d nh mt lp trnh vin vit chng trnh game cho in thoi Samsung th c th sa i chng trnh ca mnh mt cch ti thiu nht c th chy trn in thai Nokia.. Hin nay Sun a ra 2 dng Configuration: CLDC (Connected Limited Device Configuration-Cu hnh thit b kt ni gii hn): c thit k nhm vo th trng cc thit b cp thp (low-end), cc thit b ny thng thng l my in thai di ng v PDA vi khong 512 KB b nh. V ti nguyn b nh hn ch nn CLDC c gn vi Java khng dy (Java Wireless ), dng nh cho php ngi s dng mua v ti v cc ng dng Java, v d nh l Midlet. CDC- Connected Device Configuration (Cu hnh thit b kt ni): CDC c a ra nhm n cc thit b c tnh nng mnh hn dng thit b thuc CLDC nhng vn yu hn cc h thng my bn s dng J2SE. Nhng thit b ny c nhiu b nh hn (thng thng l trn 2Mb) v c b x l mnh hn. Cc sn phm ny c th k n nh cc my PDA cp cao, in thoi web, cc thit b gia dng trong gia nh C 2 dng Cu hnh k trn u cha my o Java (Java Virtual Machine) v tp hp cc lp (class) Java c bn cung cp mt mi trng cho cc ng dng J2ME. Tuy nhin, bn ch rng i vi cc thit b cp thp, do hn ch v ti nguyn nh b nh v b x l nn khng th yu cu my o h tr tt c cc tnh nng nh vi my o ca J2SE, v d,
Trang: 6
Gii thiu v J2ME cc thit b thuc CLDC khng c phn cng yu cu cc php tnh ton du phy ng, nn my o thuc CLDC khng c yu cu h tr kiu float v double.
Bng di l s so snh cc thng s k thut ca CDC v CLDC CLDC CDC Ram >=32K, <=512K >=256K Rom >=128k, <=512k >=512k Ngun Nng C GiI Hn (ngun pin) Khng gii hn Lng Network Chm Nhanh nh ngha v Profile: Profile m rng Configuration bng cch thm vo cc class b tr cc tnh nng cho tng thit b chuyn bit. C 2 Configuration u c nhng profile lin quan v t nhng profile ny c th dng cc class ln nhau. n y ta c th nhn thy do mi profile nh ngha mt tp hp cc class khc nhau, nn thng ta khng th chuyn mt ng dng Java vit cho mt profile ny v chy trn mt my h tr mt profile khc. Cng vi l do , bn khng th ly mt ng dng vit trn J2SE hay J2EE v chy trn cc my h tr J2ME. Sau y l cc profile tiu biu: Mobile Information Device Profile (MIDP): profile ny s b sung cc tnh nng nh h tr kt ni, cc thnh phn h tr giao din ngi dng vo CLDC. Profile ny c thit k ch yu nhm vo in thai di ng vi c tnh l mn hnh hin th hn ch, dung lng cha c hn. Do MIDP s cung cp mt giao din ngi dng n gin v cc tnh nng mng n gin da trn HTTP. C th ni MIDP l profile ni ting nht bi v n l kin thc c bn cho lp trnh Java trn cc my di ng (Wireless Java)
Trang: 7
Gii thiu v J2ME PDA Profile: tng t MIDP, nhng vi th trng l cc my PDA vi mn hnh v b nh ln hn Foundation Profile: cho php m rng cc tnh nng ca CDC vi phn ln cc th vin ca b Core Java2 1.3 Ngoi ra cn c Personal Basis Profile, Personal Profile, RMI Profile, Game Profile.
4. Gii thiu MIDP a) nh ngha: y l Profile c nh ngha dnh ring cho cc thit b di ng v l thnh phn chnh trong J2ME. MIDP cung cp cc chc nng c bn cho hu ht cc dng thit b di ng ph bin nht nh cc my in thoI di ng v cc my PDA. Tuy nhin MIDP khng phi l cy a thn cho mi lp trnh vin v nh chng ta bit, MIDP c thit k cho cc my di ng c cu hnh rt thp. Trong phn sau ti s lit k qua cc tnh nng m MIDP cung cp v nhng gii hn ca n. b) Nhng chc nng MIDP khng thc hin c: Php tnh du phy ng (floating point): Php tnh ny i hi rt nhiu ti nguyn CPU v phn ln cc CPU cho cc thit b di ng khng h tr php tnh ny, do MIDP cng khng c. B np class (Class Loader). H tr t kha finalize() nh trong J2SE: Vic dn dp ti nguyn trc khi n b xa c y v pha cc lp trnh vin. Khng h tr JNI H tr hn ch thao tc bt li. Phn ln cc th vin API cho Swing v AWT khng th s dng c trong MIDP. Khng h tr cc tnh nng qun l file v th mc: y c th lm bn ngc nhin nhng thc t l cc thit b J2ME khng c h tr cc thit b lu tr thng thng nh cng v.v. Tuy nhin, iu khng c ngha l bn phi mt i mi d liu quan trng mi khi tt my, Sun cung cp mt chc nng khc tng ng gi l Record Management system (RMS) cung cp kh nng lu tr cho cc thit b ny.
Trang: 8
c) Nhng chc nng MIDP cung cp Cc lp v kiu d liu: Phn ln cc lp m cc lp trnh vin Java quen thuc vn cn c gi li v d nh cc lp trong gi java.util nh Stack, Vector v Hastable cng nh Enumeration. H tr i tng Display: ng nh tn gi mt chng trnh MIDP s h tr duy nht mt i tng Display l i tng qun l vic hin th d liu trn mn hnh in thoi. H tr Form v cc giao din ngi dng. H tr Timer v Alert Cung cp tnh nng Record Management System (RMS) cho vic lu tr d liu
Ngoi ra vo thng 11 nm 2003 Sun tung ra MIDP 2.0 vi hng lot tnh nng khc c cung cp thm so vi bn 1.0. Nhng ci tin ni bt so vi MIDP 1.0 Nng cp cc tnh nng bo mt nh o Download qua mng an ton hn qua vic h tr giao thc HTTPS. o Kim sot vic kt ni gia my di ng v server: v d nh cc chng trnh khng th kt ni ti server nu thiu s chp thun ca ngi s dng. Thm cc API h tr Multimedia. Mt trong nhng ci tin hp dn nht ca MIDP 2.0 l tp cc API media ca n. Cc API ny l mt tp con ch h tr m thanh ca Mobile Media API (MMAPI). M rng cc tnh nng ca Form. Nhiu ci tin c a vo API javax.microedition.lcdui trong MIDP 2.0, nhng cc thay i ln nht (ngoi API cho game) l trong Form v Item. H tr cc lp trnh vin Game bng cch tung ra Game API: C l Sun kp nhn ra th trng y tim nng ca cc thit b di ng trong lnh vc Game. Vi MIDP 1.0 th cc lp trnh vin phi t mnh vit code qun l cc hnh ng ca nhn vt cng nh qun l ha. Vic ny s lm tng kch thc file ca sn phm cng nh vic xut hin cc on m b li. c hng li nht t Game API trong MIDP 2.0 khng ch l cc lp trnh vin Game m cn l cc lp trnh vin cn s dng cc tnh nng ha cao cp. tng c bn ca Game API l vic gi nh rng mt mn hnh game l tp hp cc layer (lp). V d nh: trong mt game ua xe th mn hnh nn l mt layer, con ng l mt layer v chic xe c xem nh ang nm trn layer khc. Vi Game API nh pht trin cn c cung cp cc tnh nng nh qun l cc thao tc bn phm. H tr kiu nh RGB: mt trong nhng ci tin hp dn cho cc nh pht trin MIDP l vic biu din hnh nh di dng cc mng s nguyn, cho php MIDlet thao tc vi d liu hnh nh mt cch trc tip. 5. Mi trng pht trin J2ME C nhiu mi trng pht trin ng dng J2ME v mi hng in thoi cng a ra nhng mi trng pht trin cho ring mnh. y ti s gii thiu toolkit ca Sun: J2ME Wireless Toolkit. a ch download chng trnh: http://java.sun.com/j2me/download.html. Ngoi ra bn cn phi c J2SDK 1.4 tr ln. Trang: 9
Sau khi hon thnh cc cc bc trn, y l lc bt u vit nhng dng code u tin. Bn nhp chut vo nt bm New Project v nhp vo tn Project v Class m bn mun to, v d TestMidlet.
Trang: 10
Gii thiu v J2ME Ch l bn khng nht thit phi to trng tn class vi tn Project. Trn ca s chng trnh s hin th cc thng bo v vic to cc th mc phc v cho vic xy dng v thc thi m chng trnh
Hy th mc : E:\WTK22\apps\Example\src, y s l ni cha source ca ng dng. Bn c th dng bt k chng trnh son tho vn bn no son code:
import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class TestMidlet extends MIDlet implements CommandListener { private Form mMainForm; public TestMidlet() { mMainForm = new Form("Lap trinh voi J2ME"); mMainForm.append(new StringItem(null, "Hello world!, MIDP!")); mMainForm.addCommand(new Command("Exit", Command.EXIT, 0)); mMainForm.setCommandListener(this); } public void startApp() { Display.getDisplay(this).setCurrent(mMainForm); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { notifyDestroyed(); } }
Sau copy source ny vo th muc ni trn. Ri tin hnh build v run chng trnh Trang: 11
Vng i ca mt MIDlet Ging nh dng chng trnh Applet trn J2SE, mt Midlet lun lun k tha javax.microedition.midlet Hm c bn nht trong mi Midlet l startApp(), hm ny s khi to Midlet cng nh vn hnh cc thnh phn hoc i tng khc, ngoi startApp(), mi Midlet cn c pauseApp() v destroyApp(), mi hm ny s c gi thc thi tng ng khi user chn dng hoc thot chng trnh.
Trang: 12
Mt i tng Screen khng phi l mt ci g hin ra trn thit b, m lp Screen ny s c tha k bi cc thnh phn hin th mc cao, chnh cc thnh phn ny s c hin th ra trn mn hnh. Hnh di y s m t mi quan h ca lp Screen v cc thnh phn th hin mc cao.
Trang: 13
Cc thnh phn giao din mc cao Tm li, phn ny ch gii thiu h thng phn cp i tng dng th hin giao din ngi dng trong MIDP. 2. Thnh phn Form v Items Trong phn ny s gii thiu cc thnh phn c hin th ra trn mt Form. Mt Form ch n gin l mt khung cha cc thnh phn, m mi thnh phn c tha k t lp Item. Chng ta s xem qua cc thnh phn hin th trn thit b trn:
DateField Gauge StringItem TextField ChoiceGroup Spacer CustomItem Image and ImageItem
a) DateField
Thnh phn DateField cung cp mt phng tin trc quan thao tc i tng Date c nh ngha trong java.util.Date. Khi to mt i tng DateField, bn cn ch r l ngi dng ch c th chnh sa ngy, chnh sa gi hay ng thi c hai. Cc phng thc dng ca lp DateField gm:
DateField(String label, int mode) DateField(String label, int mode, TimeZone timeZone)
Cc mode tng ng ca lp DateField gm:
DateField.DATE_TIME: cho php thay i ngy gi DateField.TIME: ch cho php thay i gi DateField.DATE: ch cho php thay i ngy
V d:
private DateField dfAlarm; // To mt i tng DateField vi nhn, cho php thay i c ngy v gi dfAlarm = new DateField("Set Alarm Time", DateField.DATE_TIME); dfAlarm.setDate(new Date());
Trang: 14
public DateFieldTest() { display = Display.getDisplay(this); // The main form fmMain = new Form("DateField Test"); // DateField with todays date as a default dfAlarm = new DateField("Set Alarm Time", DateField.DATE_TIME); dfAlarm.setDate(new Date()); // All the commands/buttons cmExit = new Command("Exit", Command.EXIT, 1); // Add to form and listen for events fmMain.append(dfAlarm); fmMain.addCommand(cmExit); fmMain.setCommandListener(this); fmMain.setItemStateListener(this); } public void startApp () { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void itemStateChanged(Item item) { System.out.println("Date field changed."); } public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }
Trang: 15
b) Gauge
Mt thnh phn Gauge l mt kiu giao din thng c dng m t mc hon thnh mt cng vic. C 2 loi Gauge l loi tng tc v loi khng tng tc. Loi u cho php ngi dng c th thay i Gauge, loi 2 th i hi ngi pht trin phi cp nht Gauge Di y l hm dng ca lp Gauge:
Gauge(String label, boolean interactive, int maxValue, int initialValue)
V d:
private Gauge gaVolume; // iu chnh m lng gaVolume = new Gauge("Sound Level", true, 100, 4);
Trang: 16
c) StringItem
Mt thnh phn StringItem c dng hin th mt nhn hay chui vn bn. Ngi dng khng th thay i nhn hay chui vn bn khi chng trnh ang chy. StringItem khng nhn ra s kin Phng thc dng ca lp StringItem
StringItem(String label, String text)
Trang: 17
public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmChange) { // Change label siMsg.setLabel("Section: "); // Change text siMsg.setText("developerWorks"); // Remove the command fmMain.removeCommand(cmChange); } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }
d) TextField
Mt thnh phn TextField th tng t nh bt k cc i tng nhp vn bn tiu biu no. Bn c th ch nh mt nhn, s k t ti a c php nhp, v loi d liu c php nhp. Ngoi ra TextField cn cho php bn nhp vo mt khu vi cc k t nhp vo s c che bi cc k t mt n Phng thc dng ca lp TextField
TextField(String label, String text, int maxSize, int constraints)
Thnh phn th 3 constraints l thnh phn m chng ta quan tm, v n l phng tin xc nh loi d liu no c php nhp vo TextField MIDP nh ngha cc tham s rng buc sau cho thnh phn TextField: ANY: cho php nhp bt k k t no EMAILADDR: ch cho php nhp vo cc a ch email hp l NUMERIC: ch cho php nhp s PHONENUMBER: Ch cho php nhp s in thoi URL: Ch cho php nhp cc k t hp l bn trong URL PASSWORD: che tt c cc k t nhp vo Di y l on m minh ha vic s dng thnh phn TextField
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TextFieldTest extends MIDlet implements CommandListener
Trang: 18
Trang: 19
Cc thnh phn giao din mc cao on m trn ch mi p dng mt rng buc trn i tng TextField. Chng ta c th thm mt rng buc th 2 bng cch:
tfText = new TextField.PASSWORD); TextField("Phone:", "", 10, TextField.PHONENUMBER |
e) ChoiceGroup
Thnh phn ChoiceGroup cho php ngi dng chn t mt danh sch u vo c nh ngha trc. ChoiceGroup c 2 loi: multi-selection(cho php chn nhiu mc): nhm ny c lin quan n cc checkbox exclusive-selection(ch c chn mt mc): nhm ny lin quan n nhm cc radio button Di y l on m minh ha cho vic s dng ChoiceGroup:
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ChoiceGroupTest extends MIDlet implements ItemStateListener, CommandListener { private Display display; // Reference to display object private Form fmMain; // Main form private Command cmExit; // A Command to exit the MIDlet private Command cmView; // View the choice selected private int selectAllIndex; // Index of the "Select All" option private ChoiceGroup cgPrefs; // Choice Group of preferences private int choiceGroupIndex; // Index of choice group on form public ChoiceGroupTest() { display = Display.getDisplay(this); // Create a multiple choice group cgPrefs = new ChoiceGroup("Preferences", Choice.MULTIPLE); // Append options, with no associated images cgPrefs.append("Replace tabs with spaces", null); cgPrefs.append("Save bookmarks", null); cgPrefs.append("Detect file type", null); selectAllIndex = cgPrefs.append("Select All", null); cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN,2); // Create Form, add components, listen for events fmMain = new Form(""); choiceGroupIndex = fmMain.append(cgPrefs); fmMain.addCommand(cmExit); fmMain.addCommand(cmView);
Trang: 20
Trang: 21
f) Spacer
Spacer l thnh phn khng nhn thy, c dng nh v tr cho cc i tng khc trn mn hnh hin th. Bn c th dng Spacer ch r khong trng theo chiu dc v chiu ngang gia cc thnh phn, n gin bng cch ch ra chiu di v chiu rng cho tng ci. V Spacer l thnh phn khng nhn thy nn n khng c s kin b. CustomItem Thnh phn CustomItem cho php bn to ra nhng thnh phn Item ca chnh bn. Nhng thnh phn ny cng ging nh nhng Item khc l cng c th c t vo trong Form v c th nhn bit v x l s kin CustomItem c v ln mn hnh hin th bng phng thc paint(). V th n s ty thuc vo on m c bn hin thc bn trong phng thc paint(). Qu trnh to ra mt i tng CustomItem cng khng khc cc i tng c sn trn nn Java. on m di y minh ha sn ca vic to ra mt i tng CustomItem
public class NewItem extends CustomItem { public NewItem(String label) { super(label); ... } protected void paint(Graphics g, int width, int height) { ... } protected int getMinContentHeight() { ...; } protected int getMinContentWidth() { ... } protected int getPrefContentHeight(int width) { ... }
Trang: 22
Ch : PNG l loi nh duy nht c h tr bi bt k thit b MIDP no on m di y m t vic s dng i tng Image v i tng ImageItem
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImageTest extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form
Trang: 23
public ImageTest() { display = Display.getDisplay(this); cmExit = new Command("Exit", Command.EXIT, 1); fmMain = new Form(""); fmMain.addCommand(cmExit); fmMain.setCommandListener(this); try { // Read the appropriate image based on color support Image im = Image.createImage((display.isColor()) ? "/image_color.png":"/image_bw.png"); fmMain.append(new ImageItem(null, im, ImageItem.LAYOUT_CENTER, null)); display.setCurrent(fmMain); } catch (java.io.IOException e) { System.err.println("Unable to locate or read .png file"); } } public void startApp() { display.setCurrent(fmMain); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } }
Trang: 24
Cc thnh phn giao din mc cao 3. Thnh phn List, Textbox, Alert, v Ticker
Trong phn ny chng ta s xem xt cc i tng ListBox, TextBox, Alert, v Ticker trong cc thnh phn giao din cp cao ca ng dng MIDP. Chng ta hy cng xem li cy phn cp cc thnh phn trnh by trn thit b hon chnh hn
a) List
Mt List cha mt dy cc la chn c th hin mt trong ba dng. Chng ta thy loi cho php nhiu la chn v loi ch c php chn mt khi lm vic vi ChoiceGroup. Dng th 3 l l dng khng tng minh. Cc List khng tng minh uc dng th hin mt thc n cc chn la on m di y minh ha vic s dng mt danh sch khng tng minh
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImplicitList extends MIDlet implements CommandListener { private Display display; // Reference to Display object private List lsDocument; // Main list private Command cmExit; // Command to exit public ImplicitList() { display = Display.getDisplay(this); // Create the Commands cmExit = new Command("Exit", Command.EXIT, 1); try
Trang: 25
Trang: 26
b) TextBox
TextBox c dng cho php nhp nhiu dng. Thnh phn TextBox v TextField c nhng rng buc ging nhau trong vic ch nh loi ni dung c php nhp vo. V d ANY, EMAIL, URI Di y l phng thc dng ca mt TextBox:
TextBox(String title, String text, int maxSize, int constraints)
Trang: 27
c) Alert v AlertType
Mt Alert n gin l mt hp thoi rt nh. C 2 loi Alert: Modal: l loi hp thoi thng bo c trnh by cho n khi ngi dng n nt ng Non-modal: l loi hp thoi thng bo ch c trnh by trong mt s giy nht nh Cc phng thc dng ca Alert:
Alert(String title) Alert(String title, String alertText, Image alertImage, AlertType alertType)
Thnh phn AlertType s dng m thanh thng bo cho ngi dng bit c mt s kin xy ra. V d bn c th s dng AlertType m mt on m thanh no bo hiu cho ngi dng bit khi c li xy ra Thnh phn AlertType bao gm 5 loi m thanh nh sn l: thng bo, xc nhn, bo li, thng bo v cnh bo Ta thy cc phng thc dng ca Alert cho bit l Alert c th bao gm 1 tham chiu n mt i tng AlertType. Di y l on m minh ha vic s dng Alert v AlertType
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class AlertTest extends MIDlet implements ItemStateListener, CommandListener { private Display display; // Reference to display object private Form fmMain; // Main form private Command cmExit; // Command to exit the MIDlet private ChoiceGroup cgSound; // Choice group public AlertTest() { display = Display.getDisplay(this);
Trang: 28
Trang: 29
d) Ticker
Thnh phn Ticker uc dng th hin mt on chui chy theo chiu ngang. Tham s duy nht ca thnh phn Ticker l on vn bn c trnh by. Tc v chiu cun c xc nh bi vic ci t trn thit b no. Phng thc dng ca Ticker
Ticker(String str)
T cy phn cp cc thnh phn th hin trn thit b, ta thy l thnh phn Ticker khng l lp con ca lp Screen m Ticker l mt bin ca lp Screen. iu ny c ngha l mt Ticker c th c gn vo bt c lp con ca lp Screen bao gm c Alert Di y l on m minh ha vic s dng mt Ticker
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TickerTest extends MIDlet implements CommandListener
Trang: 30
Trang: 31
Trang: 32
a) H thng trc ta
Mc tiu u tin ca chng ta l lm quen vi h thng trc ta lm vic vi thit b th hin. H thng ta cho lp Canvas c tm ta l im tri trn ca thit b trnh by. Gi tr x tng dn v pha phi, gi tr y tng dn khi i xung pha di. Khi v dy bt v l mt im nh
Trang: 33
Chiu rng v chiu cao ca Canvas cng i din cho ton b din tch khung v c th trn thit b trnh by. Ni cch khc, bn khng th ch nh kch thc cho canvas, m phn mm trn mt thit b MIDP s tr v din tch ln nht c th c i vi mt thit b cho trc
b) To mt i tng Canvas
Bc u tin lm vic vi mt lp Canvas l to ra mt lp tha k t lp Canvas
class TestCanvas extends Canvas implements CommandListener { private Command cmdExit; ... display = Display.getDisplay(this); cmdExit = new Command("Exit", Command.EXIT, 1); addCommand(cmdExit); setCommandListener(this); ... protected void paint(Graphics g) { // Draw onto the canvas ... } } TestCanvas canvas = new TestCanvas(this);
Trang: 34
Chng ta c th s dng mt tham chiu n mt i tung Graphics bn trong thn phng thc paint() thc hin cng vic v thc s
d) S kin hnh ng
Cng nh cc thnh phn Form, List, v TextBox, mt Canvas c th x l cc s Command. Chng ta c th x l cc s kin Command trn thnh phn Canvas cung cch nh cc thnh phn khc on m sau minh ha vic x l s kin Command trn thnh phn Canvas
class TestCanvas extends Canvas implements CommandListener { private Command cmdExit; ... display = Display.getDisplay(this); cmdExit = new Command("Exit", Command.EXIT, 1); addCommand(cmdExit); setCommandListener(this); ... protected void paint(Graphics g) { // Draw onto the canvas ... } public void commandAction(Command c, Displayable d) { if (c == cmdExit) ... } }
Trang: 35
e) M phm
Trong trng hp x l cc hnh ng ca cc phm mm, mt Canvas c th truy cp n 12 m phm. Nhng m ny c m bo lun lun c trn bt k cc thit b MIDP no
KEY_NUM0 KEY_NUM1 KEY_NUM2 KEY_NUM3 KEY_NUM4 KEY_NUM5 KEY_NUM6 KEY_NUM7 KEY_NUM8 KEY_NUM9 KEY_STAR KEY_POUND
Ni mt cch n gin th cc gi tr ny c nh x thnh cc phm mi tn ch hng ca thit b, nhng khng phi tt c cc thit b di ng u c nhng gi tr ny. Nu mt thit b di ng thiu cc phm mi tn th cc hnh ng ca tr chi s c nh x vo cc nt bm, v d phm tri c nh x vo phm s 2, phm phi c nh x vo phm s 5, v c tip tc nh th. Hnh di y cho thy cc hnh ng ca tr chi s c nh x ln mt thit b di ng da trn kh nng ca cc phm ch hng
Trang: 36
g) Xc nh cc hnh ng ca tr chi
on m sau y m t mt cch xc nh cc hnh ng ca tr chi t gi cc phng thc thch hp da trn cc hnh ng xy ra
protected void keyPressed(int keyCode) { switch (getGameAction(keyCode)) { case Canvas.FIRE: shoot(); break; case Canvas.RIGHT: goRight(); break; ... } }
Mt la chn na l c th to mt tham chiu cho mi hnh ng ca tr chi thng qua qu trnh khi to gi tr cho cc bin
// Initialization keyFire = getKeyCode(FIRE); keyRight = getKeyCode(RIGHT); keyLeft = getKeyCode(LEFT); ...
Trang: 37
// Runtime protected void keyPressed(int keyCode) { if (keyCode == keyFire) shoot(); else if (keyCode == keyRight) goRight() ... }
Trang: 38
/*-------------------------------------------------* Constructor *-------------------------------------------------*/ public KeyCodeCanvas(KeyCodes midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); addCommand(cmExit); setCommandListener(this); } /*-------------------------------------------------* Paint the text representing the key code *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the background (to white) g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); // Set color and draw text if (keyText != null) { // Draw with black pen g.setColor(0, 0, 0); // Center text g.drawString(keyText, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER); } } /*-------------------------------------------------* Command event handling *-------------------------------------------------*/ public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); } /*-------------------------------------------------* Key code event handling *-------------------------------------------------*/ protected void keyPressed(int keyCode) { keyText = getKeyName(keyCode); repaint();
Trang: 39
h) S kin con tr
Trong phn ny chng ta s qun l s kin con tr trong mt Canvas. Nhng s kin ny c thit k lm thun tin cho vic tng tc vi cc thit b c dng con tr. Mt s phng thc c cung cp nhm h tr cho vic x l s kin con tr:
boolean hasPointerEvents() boolean hasPointerMotionEvents() void pointerPressed(int x, int y) void pointerReleased(int x, int y) void pointerDragged(int x, int y)
Cc phng thc trn c th t gii thch chc nng thng qua tn ca chnh mnh. Phng thc hasPointerMotionEvents() tr v mt gi tr c kiu boolean nhm ch r rng thit b di ng c h tr khi nim nhp chut v r hay khng on chng trnh di y minh ha vic s dng cc s kin con tr thc hin mt chng trnh v n gin
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ScratchPad extends MIDlet { private Display display; // Display object private ScratchPadCanvas canvas; // Canvas public ScratchPad() { display = Display.getDisplay(this); canvas = new ScratchPadCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } }
Trang: 40
/*-------------------------------------------------* Class ScratchPadCanvas * * Pointer event handling *-------------------------------------------------*/ class ScratchPadCanvas extends Canvas implements CommandListener { private Command cmExit; // Exit midlet private Command cmClear; // Clear display private int startx = 0, // Where pointer was clicked starty = 0, currentx = 0, // Current location currenty = 0; private ScratchPad midlet; private boolean clearDisplay = true; /*-------------------------------------------------* Constructor *-------------------------------------------------*/ public ScratchPadCanvas(ScratchPad midlet) { this.midlet = midlet; // Create exit command and listen for events cmExit = new Command("Exit", Command.EXIT, 1); cmClear = new Command("Clear", Command.SCREEN, 1); addCommand(cmExit); addCommand(cmClear); setCommandListener(this); } /*-------------------------------------------------* Draw line based on start and ending points *-------------------------------------------------*/ protected void paint(Graphics g) { // Clear the background (to white) if (clearDisplay) { g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); clearDisplay = false; startx = currentx = starty = currenty = 0; return; } // Draw with black pen g.setColor(0, 0, 0);
Trang: 41
// Draw line g.drawLine(startx, starty, currentx, currenty); // New starting point is the current position startx = currentx; starty = currenty; } /*-------------------------------------------------* Command event handling *-------------------------------------------------*/ public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); else if (c == cmClear) { clearDisplay = true; repaint(); } } /*-------------------------------------------------* Pointer pressed *-------------------------------------------------*/ protected void pointerPressed(int x, int y) { startx = x; starty = y; } /*-------------------------------------------------* Pointer moved *-------------------------------------------------*/ protected void pointerDragged(int x, int y) { currentx = x; currenty = y; repaint(); } }
a) H tr mu
Mt ng dng MIDP ch c mt i tng Display. i tng ny uc dng ly thng tin ca mn hnh hin th hin ti, v d nh s mu h tr v cc phng Trang: 42
Cc thnh phn giao din mc thp thc yu cu cc i tng c hin th. i tng Display n gin l mt b qun l s hin th ca thit b v iu khin nhng g s c hin th ra trn thit b. boolean isColor() int numColors() Phng thc u tin cho bit thit b c h tr hin th mu hay khng. Nu c th phng thc th 2 s c gi xc nh s mu c h tr. Cc phng thc tip theo di y ly v mu v thit lp mu a thch ca bn.
void setColor(int RGB) void setColor(int red, int green, int blue) int getColor() int getBlueComponent() int getGreenComponent() int getRedComponent() void setGrayScale(int value) int getGrayScale()
Ch bn c th xc nh mu bng 2 cch. Cch 1: bn c th xc nh mt s nguyn i din cho 3 gi tr ca mu l , xanh l cy v xanh dng vi 8 bit cho mi mu. Hay cch 2 l bn c th dng tng tham s ring bit xc nh mi mu. Khi s dng mt gi tr lu gi mu, th mu s chim 8 bit u k t bn tri, tip theo l 8 bit dnh cho mu xanh l cy, sau cng l mu xanh dng. Di y s hng dn bn cch thit lp mu ch s dng mt s nguyn:
int red = 0, green = 128, blue = 255; ... g.setColor((red << 16) | (green << 8) | blue);
b) Loi nt v
Bn c th chn nt khi v ng thng, cung v hnh ch nht trn thit b hin th. Di y l cc phng thc dng thit lp loi nt v
int getStrokeStyle() void setStrokeStyle(int style)
c) V cung
Khi v mt cung, bn c th v n ch c ng bao xung quanh hay yu cu n c t bn trong. Bn c th bt u bng cch ch nh chiu bao quanh bn ngoi ca mt hnh hp ch nht tng tng. Gc bt u xc nh v tr bt u v khung, vi gi tr 0 c xc nh ti thi im 3 gi. Gi tr dng tnh theo ngc Trang: 43
Cc thnh phn giao din mc thp chiu kim ng h. Gc ca cung ch ra rng c bao nhiu c v tnh t gc ban u, i theo ngc chiu kim ng h. hiu r nhng phn ny chng ta hy cng xem1 v d sau:
g.drawArc(10, 10, 100, 100, 0, 150);
on m trn yu cu v mt cung, cung ny c bao bi mt hnh ch nht c ta im tri trn l (10, 10), chiu rng v chiu di l 100, gc bt u l 0, gc kt thc l 150
Mt s cc phng thc dng v cung void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Di y l on m minh ha vic s dng cc hm trn v mt cung
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawShapes extends MIDlet { private Display display; // The display private ShapesCanvas canvas; // Canvas public DrawShapes() { display = Display.getDisplay(this); canvas = new ShapesCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp()
Trang: 44
Trang: 45
// Change the size of the bounding box // Start at 12 o'clock and rotate 150 degrees // g.drawArc(15, 45, 30, 70, 90, 150); } public void commandAction(Command c, Displayable d) { if (c == cmExit) midlet.exitMIDlet(); } }
d) V hnh ch nht
Cng ging nh cung th hnh ch nht c th ch c v vin bao quanh hoc t bn trong. Bn cnh bn c th v hnh ch nht c 4 gc l trn hoc l vung. Di y l mt s phng thc v hnh ch nht:
void drawRect(int x, int y, int width, int height) void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) void fillRect(int x, int y, int width, int height) void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Khi v hnh ch nht c 4 gc l trn th bn phi xc nh ng knh theo chiu ngang(arcWidth) v ng knh theo chiu dc(arcHeight). Nhng tham s ny c nh ngha sc nt ca cung theo mi chiu. Gi tr cng ln th hin mt cung tng dn, ngc li l mt ng cong hp
e) Font ch
Phn sau y cng quan trng khng km l cch s dng font ch c h tr bi giao din cp thp ca ng dng MIDP. Sau y l mt s cc phng thc dng ca lp Font
Font getFont(int face, int style, int size) Font getFont(int fontSpecifier) Font getDefaultFont()
Sau khi bn c mt tham chiu n mt i tng Font, bn c th truy vn n xc nh thng tin ca cc thuc tich ca n.
int getFace() int getStyle() int getSize() boolean isPlain() boolean isBold() boolean isItalic() boolean isUnderlined()
Kch thc ca cc font ch c xc nh bi chiu cao ca font ch, b di tnh bng im nh ca mt chui k t trong mt font xc nh. Mt s cc phng thc sau h tr khi tng tc vi mt i tng font
int getHeight() int getBaselinePosition() int charWidth(char ch) int charsWidth(char[] ch, int offset, int length) int stringWidth(String str) int substringWidth(String str, int offset, int length)
f) im neo
xc nh ta x, y ca chui k t c hin th, th im neo cho php bn ch ra v tr mun t ta x, y trn hnh ch nht bao quanh chui k t
C 6 im neo c nh ngha trc, 3 theo chiu dc v 3 theo chiu thng ng, Khi xc nh im neo v chui (cc im neo thng c s dng thnh tng cp), bn phi chn mt im honh v mt im tung . Cc im neo c nh ngha nh di y
Chiu ngang LEFT (Bn tri) HCENTER (Chnh gia ca chiu ngang) RIGHT (Bn phi) Chiu dc TOP ( trn) BASELINE (ng thng c s) BOTTOM ( di)
Trang: 47
Cc thnh phn giao din mc thp Khi s dng im neo th bn cn phi ch ra ta x, y ca hnh ch nht bao quanh. V d
g.drawString("developerWorks", 0, 0 , Graphics.TOP | Graphics.LEFT);
Hnh di y m t kt qu ca hm trn
Bng cch thay i im neo, chng ta c th thay i v tr hin th ca chui k t trn thit b di ng. V d tip theo chng ta s minh ha tip khi thay i im neo th v tr ca chui k t cng thay i theo:
g.drawString("developerWorks", 0, 0 , Graphics.TOP | Graphics.HCENTER);
g) V cc chui k t
Sau khi tm hiu v font v cc im neo, bn c th v chui k t ra mn hnh thng qua mt s cc phng thc sau:
void drawChar(char character, int x, int y, int anchor) void drawChars(char[] data, int offset, int length, int x, int y, int anchor) void drawString(String str, int x, int y, int anchor) void drawSubstring(String str, int offset, int len, int x, int y, int anchor)
V d:
protected void paint(Graphics g) { // Get center of display int xcenter = getWidth() / 2, ycenter = getHeight() / 2;
Trang: 48
// Choose a font g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALICS, Font.SIZE_MEDIUM)); // Specify the center of the text (bounding box) using the anchor point g.drawString("developerWorks", xcenter, ycenter, Graphics.BASELINE | Graphics.HCENTER); }
Tip theo l v d minh ha vic s dung font v xut chui ra thit b hin th
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class FontViewer extends MIDlet { protected Display display; // The display protected PrefsForm fmPrefs; // Form to choose font prefs protected FontCanvas cvFont; // Canvas to display text (in preferred font) public FontViewer() { display = Display.getDisplay(this); cvFont = new FontCanvas(this); fmPrefs = new PrefsForm("Preferences", this); } protected void startApp() { showCanvas(); } protected void showCanvas() { display.setCurrent(cvFont); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet() { destroyApp(true); notifyDestroyed(); } } /*-------------------------------------------------* FontCanvas.java
Trang: 49
Trang: 50
Trang: 51
Trang: 52
Trang: 53
h) V nh
Lp Graphics cung cp 1 phng thc dng v nh:
drawImage(Image img, int x, int y, int anchor)
Chng ta cng p dng tng bc khi v nh cng ging nh khi xut chui ra mn hnh. i vi c 2 th chng ta u phi bt u bng vic thit lp ta x, y cng nh im neo. Danh sch cc im neo cho vic hin th nh cng khng khc my so vi vic xut chui, tuy nhin khng ging vi vic xut chui th mt bc nh c mt im trung tm. V th VCENTER c thay th cho gia tr BASELINE khi lm vic vi nh
Chiu ngang LEFT (Bn tri)
Trang: 54
Trong cc phn trc, chng ta to ra cc ng dng MIDP cho vic trnh by mt tm nh c t mt ngun ti nguyn l mt tp tin. Loi nh ny khng cho php thay i, v v vy cn c bit vi tn l nh khng th thay i. i vi v d sau y, chng ta s to ra mt tm nh t nhng ng tp nham, chng ta s cp pht b nh cho tm nh, ly tham chiu n mt i tng Graphics, v chng ta s t v ni dung tm nh. Loi nh ny cn c bit vi mt ci tn l nh c th bin thay i c
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawImage extends MIDlet { private Display display; // The display private ImageCanvas canvas; // Canvas public DrawImage() { display = Display.getDisplay(this); canvas = new ImageCanvas(this); } protected void startApp() { display.setCurrent( canvas ); } protected void pauseApp() {} protected void destroyApp( boolean unconditional ) {} public void exitMIDlet()
Trang: 55
// Draw a filled (blue) rectangle, with rounded corners graphics.setColor(0, 0, 255); graphics.fillRoundRect(0,0, im.getWidth()-1, im.getHeight()-1, 20, 20); // Center text horizontally in the image. Draw text in white graphics.setColor(255, 255, 255); graphics.drawString(message, (im.getWidth() / 2) - (font.stringWidth(message) / 2), (im.getHeight() / 2) - (font.getHeight() / 2), Graphics.TOP | Graphics.LEFT);
Trang: 56
translate() l mt phng thc c s dng c lin quan n h thng trc ta . Chng ta c th tnh tin h trc ta n mt im x, y khc. Mt s phng thc h tr cho vic tnh tin h trc ta
void translate(int x, int y) int getTranslateX() int getTranslateY()
Trang: 57
Cc hm API dnh lp trnh Game c gii thiu trong bn MIDP 2.0, nhng hm ny l phng tin pht trin game vi nhiu phn ha. Cc hm API dnh cho Game l mt phn ca gi javax.microedition.lcdui.game Lp GameCanvas gn nh ging lp Canvas, GameCanvas cung cp nn tng to giao din ngi dng, nhng trong trng hp ny ch cho vic to games. GameCanvas cha mt vng nh tch ri vi vng nh mn hnh cho mi th hin v cung cp cc phng tin tch hp xc nh tnh trng cc phm tr chi. Di y l lp GameCanvas:
public abstract class GameCanvas extends Canvas
Layer l mt lp tru tng c s dng th hin mt i tng trc quan trong mt tr chi. Sprite l mt lp con ca lp Layer, lp ny c cung cp th hin cho mt bc nh. Ngoi ra Sprite cn c th bao gm mt dy cc khung nh. thc hin kh nng chuyn ng, cc khung nh c th hin theo mt th t to hiu ng di chuyn nh. Cc php bin i nh l php quay v php lt nh c th c p dng i vi mt i tng Sprite. Di y l m t cho 2 lp Layer v Sprite
public abstract class Layer extends Object public class Sprite extends Layer
TiledLayer l mt lp tng t nh mt bng tnh, vi mi i din cho mt tm nh. Mt TiledLayer n gin c dng th hin cc phn t trc quan c kch thc ln, nh l nn ca mt tr chi.
public class TiledLayer extends Layer
n gin x l cho vic v nhiu lp trong mt tr chi, cc hm API dnh cho vic lp trnh tr chi li c th lp LayoutManager. Lp LayoutManager ny cha mt danh sch c th t cc i tng Layers v xc nh khu vc no cn c v li v th hin theo ng trt t. Lp LayoutManager c th hin nh di y:
public class LayerManager extends Object
Trang: 58
IV.
X l s kin
1. i tng Command
Khi mt i tng xy ra trn thit b di ng, mt i tng Command gi thng tin v s kin . Thng tin ny bao gm loi hnh ng thc thi, nhn ca mnh lnh v u tin ca chnh n. Trong J2ME, cc hnh ng ni chung c th hin di dng cc nt trn thit b Nu c qu nhiu hnh ng c hin th trn thit b, thit b s to ra mt thc n cha cc hnh ng Ch c cc thnh phn MIDP sau y mi c th cha cc i tng Command l: Form, TextBox, List v Canvas. Cc bc c bn x l cc s kin vi mt i tng Command: To mt i tng Command t i tng Command ln trn mt i tng Form, TextBox, List, hay Canvas To mt b lng nghe Khi c mt s kin xy ra, b lng nghe s pht sinh mt li gi n phng thc commandAction(). Trong thn phng thc ny bn c th xc nh i tng no pht sinh ra s kin v to ra cc x l tng ng Di y l on m minh ha vic to ra s kin Command v x l s kin:
private Form fmMain; // Form private Command cmExit; // Command to exit the MIDlet ... fmMain = new Form("Core J2ME"); // Create Form and give it a title // Create Command object, with label, type and priority cmExit = new Command("Exit", Command.EXIT, 1); ... fmMain.addCommand(cmExit); // Add Command to Form fmMain.setCommandListener(this); // Listen for Form events ... public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(true); notifyDestroyed(); } }
Trang: 59
2. i tng Item
Ngoi vic x l s kin bng i tng Command ta c th x l s kin bng i tng Item. Nhiu i tng trong MIDP c nh ngha trc cho vic x l cc s kin c th no . V d i tng DateField cho php ngi s dng chn la ngy v gi trn mn hnh, i tng TextField cho php ngi dng nhp vo mt chui cc k t, s v cc k t c bit Tng t nh vic x l s kin bng i tng Command, th khi c mt thay i xy ra i vi bt k thnh phn Item no th phng thc itemStateChanged() s c gi. V chng ta s thc hin cc x l bn trong phng thc ny Di y l on m minh ha vic to ra s kin Command v x l s kin:
private Form fmMain; // Form private DateField dfToday; // DateField item ... fmMain = new Form("Core J2ME"); // Create Form object dfToday = new DateField("Today:", DateField.DATE); // Create DateField ... fmMain.append(dfToday); // Add DateField to Form fmMain.setItemStateListener(this); // Listen for Form events ... public void itemStateChanged(Item item) { // If the datefield initiated this event if (item == dfToday) ... }
3. V d
Trang: 60
public EventProcessing() { display = Display.getDisplay(this); // Create the date and populate with current date tfText = new TextField("First Name:", "", 10, TextField.ANY); cmExit = new Command("Exit", Command.EXIT, 1); // Create the Form, add Command and DateField // listen for events from Command and DateField fmMain = new Form("Event Processing Example"); fmMain.addCommand(cmExit); fmMain.append(tfText); fmMain.setCommandListener(this); // Capture Command events (cmExit) fmMain.setItemStateListener(this); // Capture Item events (dfDate) } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { System.out.println("Inside commandAction()"); if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } public void itemStateChanged(Item item) { System.out.println("Inside itemStateChanged()"); } }
Trang: 61
Trang: 62
ng lin th hin vic truy xut Record store do MIDlet to ra, ng nt t l Record store do MIDlet khc to ra. Trong MIDLET Suite One, MIDlet #1 v MIDlet #2 cng c th truy xut 4 Record store. MIDLET Suite One khng th truy xut Record store trong Suite Two. Trong MIDlet Suite One tn ca cc Record store l duy nhy, tuy nhin Record store trong cc MIDlet Suite khc nhau c th dng chung mt tn. Record Store cn c 2 thuc tnh l Version Number v Date/time Stamp, cc gi tr ny thay i khi thc hin thm, thay th hay xa mt record, ngoi ra cn c th dng c ch event handler (Listener) pht hin mi khi Record store b thay i. Version number l mt s integer, bit gi tr khi u bn cn gi hm getVersion() sau khi to mt Record store. Trang: 63
Record Management System Date/time Stamp l s long integer, l s miliseconds k t ngy 1 thng 1 nm 1970, bn c th bit c gi tr ny thng qua hm getLastModified(). 2. Cc vn lin quan n RMS a) Hn ch v kh nng lu tr ca thit b di ng Dung lng vng nh (non-volatile memory) dnh ring cho vic lu tr d liu trong RMS thay i ty theo thit b di ng. c t MIDP yu cu rng cc nh sn xut thit b di ng phi dnh ra vng nh c kch thc t nht 8K cho vic lu tr d liu trong RMS. c t khng nu gii hn trn cho mi Record. RMS cung cp cc API xc nh kch thc ca mi Record, tng dung lng ca RecordStore v kch thc cn li ca vng nh ny. Do trong qu trnh pht trin cc ng dng J2ME bn phi cn nhc trong vic s dng vng nh ny. b) Tc truy xut d liu Cc thao tc trn vng nh ny (non-volatile memory) tt nhin s chm hn nhiu khi bn truy xut d liu trn b nh RAM (volatile memory). N s ging nh tc c cng v tc c t RAM ca my tnh bn. V vy trong k thut lp trnh bn phi thng xuyn cache d liu v cc thao tc lin quan n RMS ch thc hin tp trung mt ln (lc khi ng hay ng ng dng). c) C ch lung an ton Nu RecordStore ca bn ch c s dng bi mt MIDlet, bn khng phi lo lng v vn ny v RMS s dnh ring mt Thread thc hin cc thao tc trn RecordStore. Tuy nhin nu c nhiu MIDlet v Thread cng chia s mt RecordStore th phi ch n k thut lp trnh Thread m bo khng c s xung t d liu. 3. Cc hm API trong RMS RecordStore khng c hm khi to. RecordStore Class: javax.microedition.rms.RecordStore Method Description static RecordStore M mt Recordstore, c tham s to openRecordStore(String Record store nu n cha tn ti. recordStoreName, boolean createIfNecessary) void closeRecordStore() ng RecordStore. static void deleteRecordStore(String Xa RecordStore. recordStoreName) static String[] listRecordStores() Danh sch cc RecordStore trong MIDlet suite. int addRecord(byte[] data, int offset, int Thm mt record vo RecordStore. numBytes) void setRecord(int recordId, byte[] t hoc thay th mt record trong newData, int offset, int numBytes) RecordStore. Trang: 64
Record Management System void deleteRecord(int recordId) byte[] getRecord(int recordId) int getRecord(int recordId, byte[] buffer, int offset) int getRecordSize(int recordId) int getNextRecordID() int getNumRecords() long getLastModified() int getVersion() String getName() int getSize() int getSizeAvailable() RecordEnumeration enumerateRecords( RecordFilter filter, RecordComparator comparator, boolean keepUpdated) void addRecordListener (RecordListener listener) void removeRecordListener (RecordListener listener) Xa mt record trong RecordStore. Ly dy byte cha record. Ly ni dung ca record vo dy byte. Kch thc record. Ly record id ca record mi . S lng cc record. Thi gian thay i gn nht. Version ca RecordStore. Tn ca RecordStore. Kch thc ca RecordStore. S byte trng cho RecordStore. Xy dng enumeration dng duyt recordstore Add a listener to detect record store Remove listener.
Chng ta hy cng xem qua 2 v d n gin ca vic c ghi record trong RecordStore. V d 1: c v ghi i tng string (ReadWrite.java)
/*-------------------------------------------------* ReadWrite.java * * Read and write to the record store. * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class ReadWrite extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_1"; public ReadWrite() { openRecStore(); // Create the record store // Write a few records and read them back writeRecord("J2ME and MIDP"); writeRecord("Wireless Technology"); readRecords(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store
Trang: 65
Trang: 66
Trang: 67
Hm m mt recordstore
public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } }
Vi tham s true, hm s to mt RecordStore nu n cha tn ti. Trong hm WriteRecord, trc khi lu vo RecordStore, cn phi chuyn i kiu string thnh dy byte:
byte[] rec = str.getBytes(); ... rs.addRecord(rec, 0, rec.length);
Cn lu l trong v d trn do bit trc kch thc ca string nn khai bo dy byte va , trong thc t ta nn kim tra kch thc ca record khai bo dy byte cn thit trnh pht sinh li, do hm ReadRecord c th sa li nh sau:
Trang: 68
Nu ch cn c ghi nhng on text vo record, th v d trn l qu . Tuy nhin, thc t l ta cn lu nhng gi tr khc: String, int, boolean, v.v Trong v d 2 ny, chng trnh s s dng stream c v ghi record. Vic s dng stream gip chng ta linh ng v nng cao hiu qu ca vic c v ghi d liu vo RecordStore. V d 2: c v ghi s dng stream (ReadWriteStreams.java)
/*-------------------------------------------------* ReadWriteStreams.java * * Use streams to read and write Java data types * to the record store. * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class ReadWriteStreams extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_1"; // Name of record store public ReadWriteStreams() { openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { }
Trang: 69
Trang: 70
Trang: 71
Output ca v d 2:
Trang: 72
Hm s dng hai stream l strmBytes l mt mng byte s ghi vo RecordSotre v strmDataType cha d liu. Nh vy qu trnh ghi d liu vo RecordStore c thc hin thng qua cc bc: Cp pht stream. Ghi d liu vo stream. Flush stream. Chuyn i stream data thnh mng byte. Ghi mng byte vo RecordStore. ng stream. Vic c cc d liu t record n gin ch cn thay OutStream thnh InputStream:
byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); for (int i = 1; i <= rs.getNumRecords(); i++) { // Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i);
Trang: 73
Chng ta c mng byte lc u chng trnh ghi vo record, sau dng InputStream strmDataType c ng kiu d liu:
System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt());
Lu : khi s dng DataOutputStream v DataInputStream, cn phi c v ghi theo ng th t, nu khng s khng ra kt qu mong mun. 4. Duyt Record vi RecordEnumeration Trong cc v d trc duyt cc record ta s dng vng lp:
for (int i = 1; i <= rs.getNumRecords(); i++) { rs.getRecord(i, recData, 0); ... }
Ngoi ra cn mt cch khc duyt RecordStore l s dung RecordEnumeration. Lp ny cung cp cc phng thc duyt cc record trong RecordStore mt cch nhanh chng. Di y l on code duyt ton b RecordStore:
RecordEnumeration re = rs.enumerateRecords(null,null,false); while (re.hasNextElement()) { // Get the next record into a String String str = new String(re.nextRecord()); ... do something ... }
Trong on code trn s dng nextRecord() duyt n record sau , ngoi ra cn c previousRecord() gip duyt v record trc . Nu mun bt u ti v tr cui cng ca recordstore ta ch cn gi hm previousRecord() ngay khi m recordstore, n s tr v dng cui cng. RecordEnumeration c duy tr mt index ca cc record. Khi recordstore c s thay i th RecordEnumeration c th hot dng khng chnh xc, do chng ta cn phi gi hm reindex() mi khi recordstore c s thay i.
Trang: 74
Record Management System RecordEnumeration API RecordEnumeration Interface: javax.microedition.rms.RecordEnumeration Method Description int numRecords() S lng record trong enumeration byte[] nextRecord() Record tip theo int nextRecordId() Record ID ca record tip theo byte[] previousRecord() Record trc int previousRecordId() Record ID ca record trc boolean hasNextElement() Kim tra enumeration c record k tip Kim tra enumeration c record trc boolean hasPreviousElement() void keepUpdated(boolean t enumeration reindex sau khi co s keepUpdated) thay i Kim tra enumeration c t ng boolean isKeptUpdated() reindex() void rebuild() To li index void reset() a enumeration v record u tin void destroy() Gii phng ti nguyn c s dng bi enumeration 5. Sp xp cc record vi interface RecordComparator Interface ny gip ngi lp trnh so snh hai Record theo mt tiu ch no . Interface ny nh ngha phng thc compare vi tr u vo l hai mng cc byte th hin hai Record cn so snh. Phng thc ny tr v cc tr sau c nh ngha trong interface: EQUIVALENT: Nu hai Record bng nhau FOLLOWS: Nu Record th 1 ng sau Record th 2 PRECEDES: Nu Record th 1 ng trc Record th 2 Do RecrdComparator l mt interface nn khi s dng cn phi implements n:
public class Comparator implements RecordComparator { public int compare(byte[] rec1, byte[] rec2) { String str1 = new String(rec1), str2 = new String(rec2); int result = str1.compareTo(str2); if (result == 0) return RecordComparator.EQUIVALENT; else if (result < 0) return RecordComparator.PRECEDES; else return RecordComparator.FOLLOWS; } }
Trang: 75
. Enumeration s s dng hm compare trong class Comparator sp xp cc record trong RecordStore. RecordComparator Interface: javax.microedition.rms.RecordComparator Method Description int compare(byte[] rec1, byte[] rec2) So snh quyt nh th t sp xp V d 3: chng trnh sp xp c bn
/*-------------------------------------------------* SimpleSort.java * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class SimpleSort extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_1"; public SimpleSort() { openRecStore(); // Create the record store // Write a few records writeRecord("Sand Wedge"); writeRecord("One Wood"); writeRecord("Putter"); writeRecord("Five Iron"); // Read back with enumerator, sorting the results readRecords(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp()
Trang: 76
Trang: 77
Trang: 78
Record Management System Trong on code trn trong hm readRecord(), khi to Enumeration ta tham chiu n i tng comp ca lp Comparator
Comparator comp = new Comparator(); RecordEnumeration re = rs.enumerateRecords(null, comp, false); while (re.hasNextElement()) { ... }
Khi enumerator to index cho RecordStore n s s dng hm compare() trn sp xp cc record. Output ca vi d 3:
V d trn ng trong trng hp d liu lu vo record l dng text, nu quay li v d 2 ta ghi nhiu kiu d liu vo trong mt record:
// Write Java data types to stream strmDataType.writeUTF("Text 1"); strmDataType.writeBoolean(true); strmDataType.writeInt(1);
Cc kiu d liu trn s c lu vo mt stream dng binary. Sau cc stream ny s c chuyn thnh mng v a vo recordstore:
// Get stream data into an array record = strmBytes.toByteArray(); // Write the array to a record rs.addRecord(record, 0, record.length);
on code trong v d 3 s chy sai khi p dng vi kiu d liu binary. gii quyt, ta cn phi vit li hm compare() th c hin chc nng chuyn i chui byte v sp xp ng kiu d liu.
Trang: 79
Record Management System Trong thc t, chng ta cn phi lu nhiu trng d liu trong mt record nh trong v d 2 (lu d liu kiu String, boolean, integer). Trong trng hp ny s c nhiu la chn sp xp cc record, v vic la chn ny ty thuc vo ng dng ca bn. Trong 2 v d sau y s thc thi interface RecordComparator sp xp record cha nhiu kiu d liu. Nhng v d ny s s dng cng d liu u vo, tuy nhin v d 4 s sp xp da vo kiu String, trong khi v d 5 s sp xp da vo kiu integer. y l d liu s lu vo recordstore:
String[] pets = {"duke", "tiger", "spike", "beauregard"}; boolean[] dog = {true, false, true, true}; int[] rank = {3, 0, 1, 2}; Khi lu vo recordstore s c dng nh sau: Record #1 "duke" true 3 Record #2 "tiger" false 0 Record #3 "spike" true 1 Record #4 "beauregard" true 2
y l l do v d 3 khng p ng c yu cu, do d liu lu vo khng cn l dng text, v hm String.CompareTo() trn ni dung ca record khng th sp xp d liu theo mong mun. Do , bn cn phi ly ra t mi record trng d liu m bn mun sp xp. Trong v d 4 s ly kiu String u mi record, v d 5 s ly kiu integer cui mi record. V d 4: StringSort.java
/*-------------------------------------------------* StringSort.java * * Sort records that contain multiple Java * data types. Sort using String type. * * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class StringSort extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_3"; // Name of record store public StringSort()
Trang: 80
Trang: 81
Trang: 82
Trang: 83
Trang: 84
Trng d liu u tin trong cc record l kiu string, - dng lm tiu ch sp xp. Trc ht ta ly chui cn so snh trong dy byte bng hm readUTF() , ri dng compareTo() trong class String sp xp:
// Read record #1 // Only need one read because the string to // sort on is the first "field" in the record ... str1 = strmDataType.readUTF(); // Read record #2 ... str2 = strmDataType.readUTF(); // Compare record #1 and #2 int result = str1.compareTo(str2); ...
Output ca v d 4:
Trang: 85
V d 5: integer sort
/*-------------------------------------------------* IntSort.java * * Sort records that contain multiple Java * data types. Sort using integer type. * * Uses: Streams, Enumeration, RecordComparator * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class IntSort extends MIDlet { private RecordStore rs = null; // Record store static final String REC_STORE = "db_4"; // Name of record store public IntSort() { openRecStore(); // Create the record store writeTestData(); // Write a series of records readStream(); // Read back the records closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) {
Trang: 86
Trang: 87
Trang: 88
Trang: 89
Trong v d ny ta vn s dng d liu ca v d 4, tiu ch sp xp l theo kiu integer, do trc ht ta phi ly d liu trong dy byte. Tuy nhin,,c mt lu l do d liu ta cn ly nm cui cng trong dy byte do ra cn phi c theo th t, tc l phi c kiu String, boolean ri mi n integer:
// Read record #1 // We want the integer from the record, which is // the last "field" thus we must read the String // and boolean to get to the integer
Trang: 90
Output ca v d 5:
6. Searching with RecordFilter Ngoi vic sp xp cc record (s dng RecordComparator), enumerator cn cung cp c ch lc (tm kim cc record tha mn mt iu kin no ). Khi s dng RecordComparator tt c cc record trong RecordStore u c lu trong mt result set. Nhng khi dng RecordFilter, ch c nhng tha mn iu kin mi c trong enumerator result set.
class SearchFilter implements RecordFilter { private String searchText = null; public SearchFilter(String searchText) { // This is the text to search for this.searchText = searchText.toLowerCase(); }
Trang: 91
Trn y l mt class n gin thc thi interface RecordFilter. Class ny s c gn vi mt enumerator, v khi enumerator s dng hm matches() duyt ht recordstore ly ra nhng record cn tm:
// Create a new search filter SearchFilter search = new SearchFilter("search text"); // Reference the filter when creating the result set RecordEnumeration re = rs.enumerateRecords(search,null,false); // If there is at least one record in result set, a match was found if (re.numRecords() > 0) // Do something
RecordFilter Interface: javax.microedition.rms.RecordFilter Method Description boolean matches(byte[] candidate) Tm kim record tha mn mt iu kin no Sau y ta s xem qua chng trnh tm kim n gin s dng interface RecordFilter: V d 6:
/*-------------------------------------------------* SimpleSearch.java * * Display a Form and Textbox for searching records * Each record contains a String object. * * Uses: Enumeration, RecordFilter *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; import javax.microedition.lcdui.*; public class SimpleSearch extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form private StringItem siMatch; // The matching text, if any private Command cmFind; // Command to search record store private Command cmExit; // Command to insert items private TextField tfFind; // Search text as requested by user
Trang: 92
Trang: 93
Trang: 94
Trang: 95
Sau khi vit class SearchFilter, ta to mt instance search, khi khai bo class RecordEnumeration s tham chiu n instance trn. Khi ch c nhng record tha mn iu kin (trong hm matches()) mi hin th trong result set: // Setup the search filter with the user requested text SearchFilter search = new SearchFilter(tfFind.getString()); RecordEnumeration re =rs.enumerateRecords(search,null,false); // A match was found using the filter if (re.numRecords() > 0) siMatch.setText(new String(re.nextRecord()));
Trang: 96
Lu v d trn khng phn bit ch hoa thng. Tip theo y chng ta li xt thm mt v d v tm kim record. V d 7:
/*-------------------------------------------------* SearchStreams.java * * Display a Form and Textbox for searching records * Each record contains multiple Java data types * (String, boolean and integer). Use the String * data for searching * * Uses: Enumeration, RecordFilter *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; import javax.microedition.lcdui.*; public class SearchStreams extends MIDlet implements CommandListener { private Display display; // Reference to Display object private Form fmMain; // The main form private StringItem siMatch; // The matching text, if any private Command cmFind; // Command to search record store private Command cmExit; // Command to insert items private TextField tfFind; // Search text private RecordStore rs = null; // Record store static final String REC_STORE = "db_7"; // Name of record store
Trang: 97
Trang: 98
Trang: 99
Trang: 100
Trang: 101
Cng c chc nng tm kim nhng v d 7 khc v d 6 ch d liu lu vo record. v d ny d liu lu vo record di dng dy byte, v trong dy byte ny ta li lu nhiu trng d liu:
strmDataType.writeUTF(sData[i]); // Write Strings strmDataType.writeBoolean(bData[i]); // Write booleans strmDataType.writeInt(iData[i]); // Write integers
Trong hm searchRecordStore() ta to mt b tm kim v enumerator. Phng thc matches() (ca class SearchFilter) s c gi bi enumerator v c p dng cho mi record trong RecordStore. c c ng d liu cn dng ta cn dng hai stream mt dng c dy byte trong record v mt dng c ng kiu d liu trong dy byte .
strmBytes = new ByteArrayInputStream(candidate); strmDataType = new DataInputStream(strmBytes); str = strmDataType.readUTF().toLowerCase();
Trang: 102
Output:
7. Notification of Changes with RecordListener pht hin cc thay i cng nh thm vo cc Record trong RecordStore, RMS cung cp giao din RecordListener. Giao din ny nh ngha 3 phng thc, cc phng thc c 2 tr vo l mt i tng kiu RecordStore v mt s int cha recordID. Cc phng thc l: RecordListener Interface: javax.microedition.rms.RecordListener Method Description void recordAdded(RecordStore c gi khi thm 1 record recordStore, int recordId) void recordChanged(RecordStore recordStore, int recordId) void recordDeleted(RecordStore recordStore, int recordId) V d 8: s dng RecordListener Trang: 103 c gi khi record bi thay i c gi khi record b xa
/*-------------------------------------------------* RmsListener.java * * Test the RMS listener methods * * No GUI interface, all output is to the console *-------------------------------------------------*/ import java.io.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; public class RmsListener extends MIDlet { private RecordStore rs = null; static final String REC_STORE = "db_8"; public RmsListener() { // Open record store and add listener openRecStore(); rs.addRecordListener(new TestRecordListener()); // Initiate actions that will wake up the listener writeRecord("J2ME and MIDP"); updateRecord("MIDP and J2ME"); deleteRecord(); closeRecStore(); // Close record store deleteRecStore(); // Remove the record store } public void destroyApp( boolean unconditional ) { } public void startApp() { // There is no user interface, go ahead and shutdown destroyApp(false); notifyDestroyed(); } public void pauseApp() { } public void openRecStore() { try { // Create record store if it does not exist rs = RecordStore.openRecordStore(REC_STORE, true ); } catch (Exception e) { db(e.toString()); } }
Trang: 104
Trang: 105
Trang: 106
Output:
8. Exception Handling Cc phng thc trong API ca RMS ngoi vic pht sinh cc ngoi l thng thng n mi trng chy (runtime enviroment). RMS cn nh ngha thm cc ngoi l trong gi javax.microedition.rms nh sau: InvalidRecordIDException: Ngoi l ny pht sinh ra khi khng th thao tc trn Record v RecordID khng thch hp. RecordStoreFullException: Ngoi l ny pht sinh ra khi khng cn vng nh. RecordStoreNotFoundException: Ngoi l ny pht sinh ra khi m mt RecordStore khng tn ti. RecordStoreNotOpenException: Ngoi l ny pht sinh ra khi thao tc trn mt RecordStore b ng. RecordStoreException: y l lp cha ca 4 lp trn, ngoi l ny m t li chung nht trong qu trnh thao tc vi RMS.
Trang: 107
VI.
Vi kch thc hn 200 kb v hn 100 class v interfaces trong gi java.io, java.net ca J2SE s chim hu ht b nh vn d nh b ca nhng thit b i ng. Do Sun khng th k tha nhng gi ny vo trong J2ME, m h xy dng mt chun l Generic Connection Framework (GCF). GCF s gip cho cc thit b di ng c th truy xut c cc ti nguyn mng, cng nh cc ti nguyn khc m a ch ca chng c xc nh bng URL. Generic Connection Framework bao gm mt tp hp cc interfaces c khai bo trong package javax.microedition.io. Hnh v sau th hin mi quan h gia cc interfaces:
C mt class chnh l Connector v 7 interfaces c nh ngha trong GCF. T hnh v ta d dng nhn thy GCF h tr kt ni dng datagram(packet) v stream. Class Connector c dng m kt ni n mt ti nguyn no thng qua phng thc open c khai bo nh sau:
Connector.Open("protocol:address;parameters");
1. Nhng protocol c h tr trong GCF GCF h tr nhiu loi protocol khc nhau. Khi c yu cu to mt kt ni, class Connector s s dng phng thc Class.forName() tm kim mt class ph hp vi protocol . Nu tm thy mt i tng s c tr v v thc thi interface Connection (hnh v). Di y l cch m cc kt ni khc nhau: Connector.Open("socket://www.corej2me.com.com:55"); Connector.Open("http://www.corej2me.com"); Connector.Open("datagram://www.corej2me.com:1000"); Connector.Open("file://makefile.txt"); M mt kt ni to kt ni, GCF cung cp cho ta n 7 phng thc:
Connector (public class Connector) public static Connection open(String name)
Trang: 108
Tuy nhin, ngoi class ContentConnection, ta cng c th m mt kt ni trc tip bng InputStream. Sau y l on code cho php ti v mt bc nh v sau to li bc nh :
InputStream iStrm = (InputStream) Connector.openInputStream(url); Image img = null; try { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); // Place into image array byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array img = Image.createImage(imageData, 0, imageData.length); } finally { // Clean up if (iStrm != null) iStrm.close(); }
Trang: 109
The Generic Connection Framework Lu , trong on code trn do khng s dng class ContentConnection, nn ta s khng bit c kch thc ca d liu s ti v. khc phc vn ny, ngi ta s dng ByteArrayOutputStream lu d liu ti v. Di y l v d n gin, u tin MIDlet s download v hin th hnh nh ti v. MIDlet s d dng ByteArrayOutputStream cha d liu ti v:
/*-------------------------------------------------* DownloadImage.java * * Download and view a png file *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class DownloadImage extends MIDlet implements CommandListener { private Display display; private TextBox tbMain; private Form fmViewPng; private Command cmExit; private Command cmView; private Command cmBack; public DownloadImage() { display = Display.getDisplay(this); // Create the textbox, allow maximum of 50 characters tbMain = new TextBox("Enter url", "http://localhost/intel.png", 55, 0); // Create commands and add to textbox cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN, 2); tbMain.addCommand(cmExit); tbMain.addCommand(cmView ); // Set up a listener for textbox tbMain.setCommandListener(this); // Create the form that will hold the image fmViewPng = new Form(""); // Create commands and add to form cmBack = new Command("Back", Command.BACK, 1); fmViewPng.addCommand(cmBack); // Set up a listener for form fmViewPng.setCommandListener(this); }
Trang: 110
public void startApp() { display.setCurrent(tbMain); } public void pauseApp() {} public void destroyApp(boolean unconditional) {} /*-------------------------------------------------* Process events *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { // If the Command button pressed was "Exit" if (c == cmExit) { destroyApp(false); notifyDestroyed(); } else if (c == cmView) { // Download image and place on the form try { Image im; if ((im = getImage(tbMain.getString())) != null) { ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null); // If there is already an image, set (replace) it if (fmViewPng.size() != 0) fmViewPng.set(0, ii); else // Append the image to the empty form fmViewPng.append(ii); } else fmViewPng.append("Unsuccessful download."); // Display the form with image display.setCurrent(fmViewPng); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } else if (c == cmBack) {
Trang: 111
Trang: 112
2. H tr giao thc HTTP trong MIDP n y th bn d bit c rng GCF h tr nhiu kiu kt ni v pht trin ng dng MIDlet ti v v hin th hnh nh. Trong phn ny, s bn su hn v s h tr HTTP
Trang: 113
The Generic Connection Framework ca GCF. u tin, hy cp nht li s quan h gia cc interfaces trong GCF thy c v tr ca http:
c t ca phin bn MIDP 1.0 ch h tr HTTP, trong khi phin bn hin ti MIDP 2.0 h tr HTTP v HTTPS, cung cp kh nng bo mt tt hn. Cc hm API c khai bo trong HttpConnection (cho HTTP) v trong HttpConnections (cho HTTP v HTTPS).
Nhng Header field s cho php ta truyn cc tham s t client n server. Cc header field thng dng l If-Modified-Since, Accept, and User Agent. Bn c th t cc
Trang: 114
The Generic Connection Framework field ny thng qua phng thc setRequestProperty(). Di y l v d dng setRequestProperty(), ch c nhng d liu thay i sau ngy 1 thng 1 nm 2005 mi c gi v t server:
String url = "http://www.corej2me.com\somefile.txt"; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); // Set header field as key-value pair http.setRequestProperty("If-Modified-Since", "Sat, 1 Jan 2005 12:00:00 GMT"); Body cha ni dung m bn mun gi ln server. V d v s dng POST v gi d liu t client thng qua stream: String url = "http://www.corej2me.com", tmp = "test data here"; OutputStream ostrm = null; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.POST); // Send client body ostrm = http.openOutputStream(); byte bytes[] = tmp.getBytes(); for(int i = 0; i < bytes.length; i++) { os.write(bytes[i]); } os.flush();
Sau khi nhn c v s l yu cu t pha client, server s ng gi v gi v pha client. Cng nh client request, server cng gm 3 phn sau: Status line Header Body Status line s thng bo cho client kt qu ca request m client gi cho server. HTTP phn loi status line thnh cc nhm sau y: 1xx is informational 2xx is success 3xx is redirection 4xx is client error 5xx is server error Status line bao gm version ca HTTP trn server, status code, v on text i din cho status code. V d:
"HTTP/1.1 200 OK" "HTTP/1.1 400 Bad Request" "HTTP/1.1 500 Internal Server Error"
Header. Khng ging nh header ca client, server c th gi data thng qua header. Sau y l nhng phng thc dng ly thng tin Header m server gi v:
String getHeaderField(int n) Get header field value looking up by index String getHeaderField(String name) Get header field value looking up by name String getHeaderFieldKey(int n) Get header field key using index
Trang: 115
The Generic Connection Framework Server c th tr v nhiu Header field. Trong trng hp ny, phng thc u tin s cho ly header field thng qua index ca n. Cn phng thc th hai ly ni dung header field da vo tn ca header field. Cn nu mun bit tn (key) ca header field, c th dng phng thc th 3 trn. Sau y l v d v 3 phng thc trn, trong trng hp server gi v chui "content-type=text/plain". Method Return value http.getHeaderField(0) "text-plain" http.getHeaderField("content"text-plain" type") http.getHeaderFieldKey(0) "content-type" Body: Cng ging nh client, server gi hu ht nhng thng tin trong phn body cho client. Client dng input stream c kt qu tr v t server. b) The HttpConnection API Nh cp trn, ta s s dng HttpConnection API thit lp kt ni trong MIDP. Di y l nhng API trong HttpConnection: Method long getDate() long getExpiration() String getFile() int getHeaderField(int n) String getHeaderField(String name) long getHeaderFieldDate(String name, long def) int getHeaderFieldInt(String name, int def) String getHeaderFieldKey(int n) String getHost() long getLastModified() String getPort() String getProtocol() String getQuery() String getRef() String getRequestMethod() String getRequestProperty(String key) int getResponseCode() Description Get header field date Gets header field expiration Gets filename from the URL Gets header field value looking up by index Gets header field value looking up by name Gets named field as a long (representing the date) Gets named field as an integer Gets header field key using index Gets host from the URL Gets last-modified field value Gets port from the URL Gets protocol from the URL Gets the query string (only valid with GET request) Gets the reference portion of URL Gets the current setting of the request method (GET, POST or HEAD) Gets the current setting of a request property Gets the response code (numeric value) Trang: 116
The Generic Connection Framework String getResponseMessage() String getURL() void setRequestMethod(String method) void setRequestProperty(String key, String value) Gets the response message (text value) Gets the entire URL Sets the request method (GET, POST or HEAD) Sets a request property (header information)
V d: Chng ta s to mt MIDlet s dng HttpConnection ti v v hin th ni dung ca file text. Qua v d bn s hiu cch client gi request v ly response ca server. MIDlet cng s dng mt s phng thc trong HttpConnection thu thp thng tin v server: port, content type .. .
/*-------------------------------------------------* FileViewer.java *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import java.io.*; public class FileViewer extends MIDlet implements CommandListener { private Display display; private Form fmMain; private Command cmExit; private Command cmView; private String url = "http://localhost/text.txt"; public FileViewer() { display = Display.getDisplay(this); // Create exitcommand cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN, 2); // Create the form and add commands fmMain = new Form("File Viewer"); fmMain.addCommand(cmExit); fmMain.addCommand(cmView); fmMain.setCommandListener(this); } public void startApp() { display.setCurrent(fmMain); }
Trang: 117
/*-------------------------------------------------* Process events *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { // If the Command button pressed was "Exit" if (c == cmExit) { destroyApp(false); notifyDestroyed(); } else if (c == cmView) { // Download image and place on the form try { String str; if ((str = readFile()) != null) { // Delete form contents for (int i = fmMain.size(); i > 0; i--) fmMain.delete(0); // Append downloaded string fmMain.append("" + str); } } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } } /*-------------------------------------------------* Read file *-------------------------------------------------*/ private String readFile() throws IOException { HttpConnection http = null; InputStream iStrm = null; String str = null; try { // Create the connection http = (HttpConnection) Connector.open(url); //---------------// Client Request
Trang: 118
Trang: 119
Trang: 120
Console output
Trang: 121
The Generic Connection Framework 3. Accessing a Java servlet V d di y s ch cho bn tng bc cch truy truy xut java servlet. Bc u, client s truyn tham s cho servlet yu cu tr v ngy thng theo nh dng. Servlet s tr v kt qu, v s hin ln mn hnh. y l kt qu cho chui: yyyy.MM.dd+'at'+hh:mm:ss+zzz"
Trong hnh trn, ta thy phn kt qu c time zones l ICT, do ta truyn tham s zzz, nu chuyn thnh zzzz ly full text ca time zones th kt qu s thay i nh sau:
Trang: 122
The Generic Connection Framework Calling Servlet Yu cu gi servlet s uc khai bo bn trong commandAction(), v s c thc hin khi button cmRqst c kch hot:
/*-------------------------------------------------* Call the servlet *-------------------------------------------------*/ public void commandAction(Command c, Displayable s) { if (c == cmRqst) { try { serverMsg = null; callServlet(); if (serverMsg != null) fmMain.append(serverMsg); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } else if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } Di y l on code cho phng thc callServlet(), ch rng request ca client s dng request method l GET,: /*-------------------------------------------------* Call the servlet *-------------------------------------------------*/ private void callServlet() throws IOException { HttpConnection http = null; InputStream iStrm = null; boolean ret = false; // Examples - Data is passed at the end of url for GET String url = "http://localhost:8080/j2me/dateformatservlet?format=MMMM.dd.yyyy+''+hh:mm+aa"; // String url = "http://localhost:8080/j2me/dateformatservlet?format=yyyy.MM.dd+'at'+hh:mm:ss+zzz"; try { http = (HttpConnection) Connector.open(url); //----------------
Trang: 123
Code cho servlet, hu ht cc phng thc u c bit trong doPost(), bin format dng lu request t client, sau servlet s gi SimpleDateFormat to ra kt qu ph hp vi request:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.Date; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.util.Locale; public class DateFormatServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
Trang: 124
MIDlet nhn kt qu tr v t servlet, trc ht phi kim tra status line vi server v c kt tr v kt qu hay khng (HTTP_OK). Do khng c thng tin header nn s tin hnh ly kt qu t input stream:
/*-------------------------------------------------* Process a response from a server *-------------------------------------------------*/ private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException { //Reset error message errorMsg = null; // 1) Get status Line if (http.getResponseCode() == HttpConnection.HTTP_OK) { // 2) Get header information - none // 3) Get body (data) int length = (int) http.getLength(); String str; if (length != -1) { byte servletData[] = new byte[length]; iStrm.read(servletData); str = new String(servletData); }
Trang: 125
Trang: 126
Ph lc
Ph lc
Bng 1: Tng s class v interface trong CLDC Tn gi Miu t java.io Qun l vic xut nhp ca h thng java.lang Cc lp Java c bn java.util Cc lp h tr vic tnh thi gian, qun l tp hp v.v javax.microedition Qun l kt ni Bng 2: Cc lp b sung trong MIDP 1.0 Tn gi Miu t javax.microedition.rms Qun l vic lu tr d liu javax.microedition.midlet Giao din trung gian gia Midlet v mi trng Midlet ang chy javax.microedition.io H tr HTTP javax.microedition.lcdui H tr giao din ngi dng Bng 3: Tng s class v interface trong CDC Tn gi Miu t java.io Qun l vic xut nhp ca h thng java.lang Cc lp Java c bn java.lang.ref Cc lp h tr b thu gom rc ca JVM java.lang.reflect H tr tnh nng reflection trong Java java.math H tr cc php tnh trong ton hc java.net H tr mng java.security Cung cp cc tnh nng bo mt java.security.cert H tr cc chng thc trong bo mt java.text Cung cp cc lp h tr thao tc trn text java.util Cc lp h tr vic tnh thi gian, qun l tp hp v.v java.util.jar H tr thao tc trn file Jar java.util.zip H tr thao tc trn file Zip javax.microedition Qun l kt ni S lng class v interface 18 38 10 10 S lng class v interface 10 2 1 24 S lng class v interface 62 77 5 12 1 23 36 4 13 47 7 9 10
Trang: 127
Ph lc
Tham kho: http://java.sun.com/j2me/ http://www.cs.armstrong.edu/burge/pdf/huc/01_J2ME_Overview.pdf http://www.onjava.com/pub/a/onjava/2001/03/08/J2ME.html http://developers.sun.com/techtopics/mobility/midp/articles/wtoolkit/ CLDC Specification (JSR-30) http://www.jcp.org/jsr/detail/30.jsp CLDC Next Generation (JSR-139) http://www.jcp.org/jsr/detail/139.jsp MIDP Specification (JSR-37) http://www.jcp.org/jsr/detail/37.jsp Mobile Information Device Next Generation (JSR-118) http://www.jcp.org/jsr/detail/132.jsp PDA Profile Specification (JSR-75) http://www.jcp.org/jsr/detail/75.jsp CDC Specification (JSR-36) http://www.jcp.org/jsr/detail/36.jsp Foundation Profile Specification (JSR-46) http://www.jcp.org/jsr/detail/46.jsp Personal Profile Specification (JSR-62) http://www.jcp.org/jsr/detail/62.jsp RMI Profile Specification (JSR-66) http://www.jcp.org/jsr/detail/66.jsp Java Game Profile (JSR-134) http://www.jcp.org/jsr/detail/134.jsp J2ME Multimedia API Specification (JSR-135) http://www.jcp.org/jsr/detail/135.jsp J2ME White Papers KVM http://java.sun.com/products/cldc/wp Applications for Mobile Devices http://java.sun.com/j2me/docs/pdf/midpwp.pdf J2ME Technologies J2ME http://java.sun.com/j2me CLDC and KVM http://java.sun.com/products/cldc MIDP http://java.sun.com/products/midp MIDP for Palm OS http://java.sun.com/ CDC and CVM http://java.sun.com/products/cdc
Trang: 128
Ph lc J2ME Development Kits J2ME Wireless Toolkit http://java.sun.com/products/j2mewtoolkit Metrowerks CodeWarrior for J2ME http://www.metrowerks.com/desktop/java Zucotto WHITEboard SDK http://www.zucotto.com/whiteboard/index.html RIM BlackBerry Java IDE http://developers.rim.net/tools/jde/index.shtml J2ME Developer Resources Java Developer Connection http://developer.java.sun.com/developer Java Wireless Developer Initiative http://java.sun.com/wireless Wireless Developer Network http://www.wirelessdevnet.com Micro Java Network http://www.microjava.com Java Mobile Community http://www.javamobile.org Java Enabled Phones and PDAs http://www.javamobiles.com KVM World http://www.kvmworld.com KVM-Interest Mailing List Archive http://archives.java.sun.com/kvm-interest.html XML Parsers for J2ME TinyXML Parser http://gibaradunn.srac.org/tiny NanoXML Parser http://nanoxml.sourceforge.net
Trang: 129