Professional Documents
Culture Documents
Gio trnh
Java v cng ngh
J2ME
J2ME (Java 2 Platform, Micro Edition): Bao gm mi trng v th vin Java dng
pht trin cc ng dng trn cc thit b c b nh nh nh in thoi di ng, PDA, cc
gia dng.
Gii thiu v J2ME v lp trnh cho thit b di ng
J2ME c pht trin t kin trc JavaCard, EmbededJava v PersonalJava ca
phin bn Java 1.1. Sau s ra i ca phin bn Java 2 th Sun quyt nh thay th
PersonalJava bng mt phin bn mi c tn Java 2 Micro Edition, vit tt l J2ME. J2ME
c s dng cho cc thit b nh gn vi dung lng b nh nh b v kh nng x l
thp.
Mc tiu ca Java l cho php ngi lp trnh vit cc ng dng c lp vi thit b
di ng., khng cn quan tm n phn cng thc s. lm c nh vy, J2ME c
xy dng bng cc tng khc nhau che giu i vic tng tc trc tip vi phn cng
ca thit b. Cc tng ca J2ME c xy dng trn CLDC (Connected Limited Device
Configuration):
Tng di cng l tng Phn cng thit b - y l tng vt l bao gm phn cng ca
thit b di ng. Cc tng bn trn tng Phn cng thit b l cc tng tru tng, chng
cung cp cho lp trnh vin nhiu giao din lp trnh thn thin v d dng hn m khng
cn quan tm n phn cng. Ni cc khc chng ng vai tr trung gian gip cho lp
trnh vin tng tc c vi phncng m khng cn quan tm n cc chi tit thc s
ca phn cng ca thit b.
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 (JavaWireless ), 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
4
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, 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.
Ram
Rom
CLDC
>=32K, <=512K
>=128k, <=512k
CDC
>=256K
>=512k
Network
Cham
Nhanh
b) 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 htr J2ME.
Sau y l cc profile tiu biu:
Mobile Information Device Profile (MIDP): profile ny s b sung cc tnh nng
nh htr 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)
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.
M ngun chng trnh c th c bin dch bng cc trnh bin dch chun ca Java,
chng to ra cc file .class. Ta c th bin dch t cc trnh son tho hoc bin dch
trc tip t dng lnh..
6.4 Kim tra li v chy th
6.5 ng gi
Sau khi kim li v chy th chng trnh, chng ta tin hnh ng gi ng dng
c th ci t trn cc thit b tht. Vic ng gi ng dng thc cht l nn cc file
.class vo trong mt file .jar, iu ny gip gim kch thc ng dng v n gin ha
khi ci t trn thit b tht. Chng ta c th ng gi ng dng bng trnh ng gi ca
JDK hoc trnh ng gi nm trong cc IDE. Hoc mt cch rt th cng, chng ta c
th ng gi ng dng mt cch trc tip. Vic ng gi trc tip thc cht cng tin
hnh li cc cng vic nh cc trnh ng gi nhng chng ta c th kim sot li tt
hn. Tuy vy vic ny kh phc tp v d gy ra li nu lp trnh vin cha thun thc.
6.6 ng gi v trin khai ng dng thnh tp tin JAR
Cc lp c bin dch ca ng dng J2ME c ng gi trong tp tin JAR
cng vi cc ti nguyn khc nh: hnh nh, m thanh,... Tp tin JAR ny chnh l tp tin
c ci vo thit b di ng. Ngi s dng c th ti tp tin JAR vo my di ng bng
cc cch sau:
Kt ni in thoi di ng vi my tnh bng cp truyn d liu: Vic ny yu cu
ngi dng phi c tp tin JAR tht s v phn mm truyn thng ti ng dng vo in
thoi thng qua cp d liu
Cng hng ngoi: Yu cu thit b di ng v ngun cha file JAR phi h tr hng ngoi
v ngi dng c file JAR tht s
S dng mng khng dy: ti ng dng thng qua mng GPRS, ngi dng ch cn bit a
ch URL ca tp tin JAR.
6.7 Tp tin manifest.mf v tp tin JAD
Tp tin manifest.mf v tp tin JAD m t cc c im ca ng dng. Tp tin
manifest.mf nm bn trong tp tin JAR cn tp tin JAD nm ngoi tp tin JAR. Tp tin
JAD gip cho ngi dng c th bit c c im ca ng dng trc
khi ti. Vic ny gip lm gim lng ph ti nguyn v tin bc v trn thc t, mt ng
dng J2ME no ch c th chy trn mt s my nht nh.
Tp tin manifest.mf c ni dung nh sau:
Manifest-Version: //Phin bn tp tin manifest.mf
MIDlet-Name://Tn b MIDlet
MIDlet-Version: //Phin bn ca b MIDlet
MIDlet-Vendor: //Nh sn xut
MIDlet-<n>://Tn ca MIDlet chnh
MicroEdition-Profile:
MicroEdition-Configuration:
//Phin bn cu hnh
Phn ln cc th vin API cho Swing v AWT khng th s dng c trong MIDP.
Nokia series 40
Motorola T720
Panasonic X60
64 KB
64KB
80KB
128KB
100KB
10
11
12
chi
MIDletStateChangeException.
Di y l vng i ca mt MIDlet:
13
MIDlet ang t trng thi PAUSED chuyn n thc thi phng thc startApp()
thng qua phng thc resumeRequest(): phng thc ny yu cu MIDlet chuyn
vo ch hot ng.
MIDlet ang trng thi hot ng chuyn n thc thi phng thc pauseApp() thng qua
phng thc notifyPaused(): phng thc ny cho bit MIDlet t nguyn chuyn sang
trng thi dng.
MIDlet ang trng thi no chuyn n thc thi phng thc destroyApp() thng qua
phng thc notifyDestroyed(): phng thc ny cho bit MIDlet sn sng hy. T
chng ta c th thy 3 phng thc mi ny t MIDlet vo trng thi trung gian gia
cc trng thi khc.
1.2 itng Display
Mi MIDlet c mt tham chiu n mt i tng Display. i tng ny cung cp
cc thng tin v mn hnh cng nh mt s phng thc cn cho vic hin th cc i
tng khc trn mn hnh. C th xem Display l i tng c nhim v qun l vic hin
th ca mn hnh. Chc nng ca n l quyt nh danh sch cc thnh phn cn xut hin
trn mn hnh cng nh thi im ph hp hin th chng.
1.3 i tng Displayable
Mc d mi MIDlet ch c duy nht mt i tng Display nhng n li c th c
rt nhiu i tng Displayable. iu c ngha l mt i tng Display c th hin th
bao nhiu i tng Displayable ty . i tng Displayable l i tng c th nhn thy
c mt cch trc quan trn mn hnh. Bn thn MIDP c cha 2 lp con ca Displayable
l Screen v Canvas:
public abstract class Displayable
public abstract class Canvas extends Displayable
public abstract class Screen extends Displayable
14
15
Tm li, phn ny ch gii thiu h thng phn cp i tng dng th hin giao din ngi
dng trong MIDP.
2.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:
DateField
Gauge
StringItem
TextField
ChoiceGroup
Spacer
CustomItem
Image and ImageItem
a) DateField
16
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)
VI du:
private DateField dfAlarm; // Tao doi tuong DateField cho thay doi ca ngay va gid dfAlarm =
new DateField("Set Alarm Time", DateField.DATE TIME); dfAlarm.setDate(new Date());
Di y l on chng trnh mu th nghim i tng DateField
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;
public class DateFieldTest extends MIDlet implements ItemStateListener,
CommandListener {
private Display display; // Reference to display object
private Form fmMain; // Main form
private Command cmExit; // Exit MIDlet
private DateField dfAlarm; // DateField component
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);
17
dfAlarm.setDate(new Date());
fmMain.addCommand(cmExit);
fmMain.setCommandListener(this);
fmMain.setItemStateListener(this);
}
public void startApp () {
display.setCurrent(fmMain);
}
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {} public
void itemStateChanged(Item item) {
System.out.println("Date field changed.");
}
}
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)
VI du:
private Gauge gaVolume; // iu chnh m lng
gaVolume = new Gauge("Sound Level", true, 100, 4);
Di y l on chng trnh mu minh ha cch s dng lp Gauge
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InteractiveGauge extends MIDlet implements CommandListener {
private Display display; // Reference to display object
private Form fmMain; // The main form
18
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) { if (c ==
cmExit) {
destroyAppfalse); notifyDestroyed();
}
}
}
c) Stringltem
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)
Duoi day la doan ma minh hoa viec su dung doi tuong Stringltem
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
19
public voidpauseApp() {}
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();
20
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 dliu 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 sin 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{
private Display display; // Reference to Display object private Form fmMain; //
Main form private Command cmTest; // Get contents of textfield private
Command cmExit; // Command to exit the MIDlet private TextField tfText; //
Textfield public TextFieldTest() {
display = Display.getDisplay(this); // Create
commands
cmTest = new Command("Get Contents", Command.SCREEN, 1);
21
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) { if (c ==
cmTest) {
System.out.println("TextField contains: " + tfText.getString());
}
else if (c == cmExit) {
destroyApp(false); notifyDestroyed();
}
}
}
new
TextField("Phone:",
"",
10,
TextField.PHONENUMBER
TextField.PASSWORD);
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
22
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
23
f ) Spacer
Spacer l thnh phn khng nhn thy, c dng nh v tr cho cc i tng khc
trn mn hnh hin th. Chng ta 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.
g) Customltem
24
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 thc 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);
}
25
createImage(InputStream stream)
Image createRGBImage(int[] rgb, int width, int height, boolean processAlpha)
ImageItem(String label, Image img, int layout, String altText)
on m di y m t lm th no to mt tm nh t mt tp tin, v gn n vi mt i
tng ImageItem v thm mt bc nh vo mt Form:
Form fmMain = new Form("Images"); ... //
Create an image
Image img = Image.createImage("/house.png");
// Append to a form
fmMain.append(new ImageItem(null, img, ImageItem.LAYOUTCENTER, null));
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 private Command cmExit; // Command to exit the MIDlet public
ImageTest() {
26
display = Display.getDisplay(this);
cmExit = new Command("Exit", Command.EXIT, 1);
fmMain = new Form("");
fmMain.addCommand(cmExit);
fmMain.setCommandListener(this);
try{
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) { if (c
== cmExit) {
destroyApp(false); notifyDestroyed();
}
}
}
27
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
28
catch (java.io.IOException e) {
System.err.println("Unable to locate or read.png file");
}
}
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) { // If
an implicit list generated the event if (c == List.SELECT
COMMAND) {
switch (lsDocument.getSelectedIndex()) { case 0:
System.out.println("Next selected");
break;
case 1:
System.out.println("Previous selected");
break;
case 2:
System.out.println("New selected");
break;
}
29
else if (c == cmExit) {
destroyApp(false); notifyDestroyed();
}
}
}
b) TextBox
TextBox c dng cho php nhp nhiu dng. Thnh phn TextBox v
TextField c nhng rng buc ging nhau trong vic chnh 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)
c) Alert va 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 chc trnh by trong mt s giy nht nhCc
phng thc dng caAlert:
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..
30
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {} public void
commandAction(Command c, Displayable s) { if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
}
31
if (al != null) {
// Wait for user to acknowledge the alert al.setTimeout(A
lert.FOREVER); // Display alert, show main form when done
display.setCurrent(al, fmMain);
}
}
}
d) Ticker
Thnh phn Ticker uc dng th hin mt on chui chy theo chiungang.
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 cngha l mt
Ticker c th c gn vo bt c lp con ca lp Screen bao gm c Alert
Duoi day la doan ma minh hoa viec su dung mot Ticker
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TickerTest extends MIDlet implements CommandListener {
private Display display; // Reference to Display object private List
lsProducts; // Products private Ticker tkSale; // Ticker
32
else if (c == cmExit) {
destroyApp(true); notifyDestroyed();
}
}
}
33
H thng ta
To i tng Canvas
X l cc s kin hnh ng
34
36
}
}
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
KEYNUM0
KEYNUM1
KEYNUM2
KEYNUM3
KEYNUM4
KEYNUM5
KEYNUM6
KEY_NUM7
KEYNUM8
KEYNUM9
KEYSTAR
KEYPOUND
37
38
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
39
40
public KeyMappingQ {
display = Display.getDisplay(this); canvas = new
KeyCodeCanvas(this);
}
protected void startApp() {
display.setCurrent( canvas );
}
protected voidpauseApp() {}
protected void destroyApp( boolean unconditional) {} public void
exitMIDlet() {
destroyApp(true);
notifyDestroyed();
}
}
protected voidpaint(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);
}
}
public void commandAction(Command c, Displayable d) {
41
if (c == cmExit) midlet.exitMIDlet();
protected void keyPressed(int keyCode) { keyText =
getKeyName(keyCode); repaint();
}
}
h) S kin con tr
Trong phn ny chng ta s qun l s kin con tr trong mt Canvas. Nhng skin
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()
voidpointerPressed(int x, int y)
voidpointerReleased(int x, int y)
voidpointerDragged(int x, int y)
Cc phng thc trn c th t gii thch chc nng thng qua tn ca chnh mnh.
V d nh 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 thchin 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);
}
42
display.setCurrent( canvas );
protected voidpauseApp() {}
protected void destroyApp( boolean unconditional){}
public void exitMIDlet() {
destroyApp(true); notifyDestroyed();
}
}
protected voidpaint(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;
}
43
// Draw line
g.drawLine(startx, starty, currentx, currenty); // New starting point is
the current position startx = currentx; starty = currenty;
}
public void commandAction(Command c, Displayable d) { if (c == cmExit)
midlet.exitMIDlet(); else if (c == cmClear) {
clearDisplay = true;
repaint();
}
}
3.3 Lp Graphics
Chng ta s dng i tng Graphics v ln mt Canvas.
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 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 sc hin th ra trn thit b.
C hai phng thc chng ta cn quan tm n:
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
44
b) Loi nt ve
Bn c th chn nt khi vng thng, cung v hnh ch nht trn thit b hin th. Di y
l cc phng thc dng thit lp loi nt ve
int getStrokeStyle() void setStrokeStyle(int style) Hai kieu net ve duoc dinh nghia
trong lop Graphics la net cham, va net lien
g.setStrokeStyle(Graphics.DOTTED
g.setStrokeStyle(Graphics.SOLID);
c) V cung
45
startAngle
'OC100
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
46
new
protected voidpauseApp() {}
protected void destroyApp( boolean unconditional) {}
public void exitMIDlet() { destroyApp(true);
notifyDestroyed();
}
class ShapesCanvas extends Canvas implements CommandListener { private
Command cmExit; //Exit midlet private DrawShapes midlet; public
ShapesCanvas(DrawShapes midlet) { this.midlet = midlet;
// Create exit command and listen for events cmExit = new Command("Exit",
Command.EXIT, 1); addCommand(cmExit); setCommandListener(this);
}
d) V hnh ch nht
47
Cng ging nh cung th hnh ch nht c th chc 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 chc 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() Mot so
thuoc tinh cua lop Font FACESYSTEM
FACEMONOSPACE FACEPROPORTIONAL
STYLEPLAIN STYLEBOLD STYLEITALIC
STYLEUNDERLINED SIZESMALL SIZEMEDIUM
SIZELARGE
Cc tham s kiu dng c th c kt hp thng qua ton t | . V du
Font font = Font.getFont(Font.FACE_SYSTEM ,Font.STYLEBOLD |
Font.STYLE ITALIC, Font.SIZE SMALL);
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 tnh ca n.
int getFace()
int getStyle()
int getSize()
boolean isPlain()
boolean isBold()
boolean isItalic()
boolean isUnderlined()
48
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), ta phi chn
mt im honh v mt im tung . Cc im neo c nh ngha nh di y:
Chieu ngang
-
Chieu doc
-
TOP (d tren)
BOTTOM (d duoi)
49
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) 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)
Vi du:
protected voidpaint(Graphics g) { // Get
center of display int xcenter = getWidth() / 2,
ycenter = getHeight() / 2; // Choose a font
g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLEBOLD,
50
Font.SIZESMALL)); // 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 thi:
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 voidpauseApp() {}
protected void destroyApp( boolean unconditional) {}
public void exitMIDlet() {
destroyApp(true); notifyDest
}
}
/*-----------------------------------------------------* FontCanvas.java
* __________________________________ */
import javax.microedition.lcdui.*;
class FontCanvas extends Canvas implements CommandListener { private
int
face, // Font face style, // style size; // size
private String text = "developerWorks"; // Text to display in preferred font private Command
cmExit; // Exit midlet private Command cmPrefs; // Call the preferences form private
FontViewer midlet; //Reference to the main midlet public FontCanvas(FontViewer midlet) {
this.midlet = midlet;
51
52
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 nhim
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
thVCENTER c thay th cho gia tr BASELINE khi lm vic vi nh.
Chieu ngang
-
Chieu doc
-
53
}
/*
* Class ImageCanvas *
* _______________________________ */
class ImageCanvas extends Canvas implements CommandListener {
private Command cmExit; //Exit midlet
private DrawImage midlet;
private Image im = null;
private String message = "developerWorks";
public ImageCanvas(DrawImage midlet) {
this.midlet = midlet; // Create exit command and listen for events
cmExit = new Command("Exit", Command.EXIT, 1);
addCommand(cmExit);
setCommandListener(this);
try{
// Create mutable image
im = Image.createImage(100, 20);
// Get graphics object to draw onto the image
Graphics graphics = im.getGraphics();
// Specify a font face, style and size
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE PLAIN, Font.SIZE
MEDIUM); graphics.setFont(font);
// Draw a filled (blue) rectangle, with rounded corners graphics.setColor(0, 0, 255);
54
55
56
of
of
of
57
58
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 coth 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 cn gi hm getVersion() sau khi to mt Record store.
Date/time Stamp l s long integer, l s miliseconds k t ngy 1 thng 1 nm 1970, chng ta
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 lp trnh vin 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 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. V vy trong k thut lp trnh 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.
59
60
Chng ta hy cng xem qua v d n gin ca vic c ghi record trong RecordStore. V d:
c v ghi i tng string (ReadWrite.java)
/*--------------------------------------------------------------------* ReadWrite.java
*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class ReadWrite extends MIDlet {
private RecordStore rs = null;
static final String RECSTORE = ndb_1n;
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
61
}
public void destroyApp( boolean unconditional) {}
public void startApp() {
// There is no user interface, go ahead and shutdown
destroyAppfalse);
notifyDestroyed();}
public voidpauseApp() {}
public void openRecStore() {
try {
// Create record store if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true);
}
}
}
62
Hm m mtrecordstore
public void openRecStore() {
// 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:
63
byte[] previousRecord()
int previousRecordId()
boolean hasNextElement()
boolean hasPreviousElement()
void keepUpdated(boolean
keepUpdated)
boolean isKeptUpdated()
void rebuild()
void reset()
void destroy()
Record truoc do
Record ID cua record truoc do
Kiem tra enumeration co record ke tiep
Kiem tra enumeration co record truoc do
Dat enumeration reindex sau khi co
suthay doi
Kiem tra enumeration co tudong
reindex()
Tao lai index
Dua enumeration ve record dau tien
Giai phong tai nguyen duoc su dung boi
enumeration
65
rs = RecordStore.openRecordStore(REC_STORE, true);
}
67
}
private void db(String str) {
System.err.println("Msg: " + str);
}
class Comparator implements RecordComparator { public
int compare(byte[] reel, byte[] rec2) { Stringstrl = new
String(recl), 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;
}
}
Trong doan code tren trong ham readRecord(), khi tao Enumeration ta da tham chieu den doi
tuong comp cua lop Comparator
Comparator comp = new Comparator();
68
strmDataType.writeBoolean(true);
strmDataType.writeInt(1);
69
---------------- */
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 RECSTORE = "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
}
70
catch (Exception e) {
db(e.toString());
}
}
71
strmDataType.writeUTF(sData[i]);
strmDataType.writeBoolean(bData[i]);
strmDataType.writeInt(iData[i]); // Clear any buffered data
strmDataType.flush ();
// Get stream data into byte array and write record
record = strmBytes.toByteArray();
rs.addRecord(record, 0, record.length);
// Toss any data in the internal array so writes
// starts at beginning (of the internal array)
strmBytes.reset();
}
strmBytes.close();
strmDataType.close();
}
catch (Exception e) {
db(e.toString());
}
}
while
72
strmBytes.close(); strmDataType.close();
}
catch (Exception e) {}
}
73
catch (Exception e) {
return RecordComparator.EQUIVALENT;
}
}
}
74
x2 = strmDataType.readInt();
// Here's our data
// Compare record #1 and #2
5. Tm Kim Vi B Lc 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();
}
public boolean matches(byte[] candidate) {
String str = new String(candidate).toLowerCase(); //Look for a match
if (searchText != null && str.indexOf(searchText) != -1) return true; else return false;
75
Sau y ta s xem qua chng trnh tm kim n gin s dng interface RecordFilter:
Vi du:
/* -------------------------------------------------------------------* SimpleSearch.java *
*/
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
private RecordStore rs = null; // Record store
static final String RECSTORE = "db_6"; // Name of record store public
SimpleSearch() {
display = Display.getDisplay(this);
tfFind = new TextField("Find", "", 10, TextField.ANY);
siMatch = new StringItem(null, null);
cmExit = new Command("Exit", Command.EXIT, 1);
cmFind = new Command("Find", Command.SCREEN, 2);
76
RecordStore.deleteRecordStore(RECSTORE);
}
78
else if (c == cmExit) {
destroyApp(false); notifyDestroyed();
}
}
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()));
Output:
79
80
Vi du : su dung RecordListener
/*--------------------------------------------------------------------* RmsListener.java *
*/
import java.io.*;
import javax.microedition.midlet.*; import
javax.microedition.rms.*; public class RmsListener
extends MIDlet { private RecordStore rs = null; static
final String RECSTORE = "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();
}
81
try {
rs.closeRecordStoreQ;
}
catch (Exception e) {
db(e.toString());
}
}
catch (Exception e) {
db(e.toString());
}
}
catch (Exception e) {
db(e.toString());
}
}
catch (Exception e) {
db(e.toString());
82
}
public void dbfString str) {
System.err.println("Msg: " + str);
}
}
class TestRecordListener implements RecordListener {
public void recordAdded(RecordStore recordStore, int recordId) {
try {
System.out.println("Record with ID#: " + recordId + "added to RecordStore: "
+ recordStore.getName());
}
catch (Exception e) {
System.err.println(e);
}
}
catch (Exception e) {
System.err.println(e);
}
}
catch (Exception e) {
System.err.println(e);
}
}
}
83
84
85
Class.forName("com.sun.midp.io.j2me.http.Protocol");
Khi tm thy lp tng ng, Class.forName() s tr v mt i tng c ci
t giao din Connection (trong lp Connector v giao din Connection c
nh ngha sn trong CLDC) Sau y l cy phn cp Connection, n bao gm cc
lp
mi
lp
nh
ngha
nh
mt
giao
din:
86
2. Kt ni HTTP
HTTP l giao thc duy nht chc chn c h tr bi MIDP 1.0. Chng ta c th giao tip
vi my ch hay bt k thit b t xa no c h tr giao thc ny nh vo lp
HttpConnection. Lp Connector cung cp cho ngi dng by phng thc to kt ni
ti my ch. Ba phng thc trong s l cc bin th ca phng thc open(). Cc
phng thc ny c m t trong bng sau:
name)
READWRITE
static Connection open(String name, int Tao mot ket noi voi che do duoc
mode)
chi dinh
Tao mot ket noi voi che do
openInputStream(String name)
static OutputStream
openOutputStream(String name)
static DataInputStream
openDataInputStream(String name)
DataInputStream
static DataOutputStream
Tao ket noi luong xuat kieu
openDataOutputStream(String
DataOutputStream
name)
87
88
/* --------------------------------------------------------------------* DownloadImage.java *
*/
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);
}
public void startApp() {
display.setCurrent(tbMain);
}
public voidpauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
89
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.LAYOUTDEFAULT, 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.setCurrentfmViewPng);
}
catch (Exception e) {
System.err.println("Msg: " + e.toString());
}
}
else if (c == cmBack) {
display.setCurrent(tbMain);
}
}
finally {
// Clean up
if (iStrm != null)
iStrm.close();
}
Request method
Header
Body
92
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.
Vi du: "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.
93
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 "contenttype=text/plain".
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. 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()
Description
Get header field date
Gets header field expiration
94
String getFile()
int getHeaderField(int n)
String getHeaderField(String name)
long getHeaderFieldDate(String
date)
int getResponseCode()
String getResponseMessage()
String getURL()
property
Gets the response code (numeric value)
Gets the response message (text value)
Gets the entire URL
void setRequestMethod(String
method)
HEAD)
Sets a request property (header information)
95
96