graphics, threads and httpconnections in midlets

Post on 20-May-2015

2.052 Views

Category:

Education

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Graphics, Threading and HTTP-Connection in MIDP

Jussi PohjolainenTAMK University of Applied Sciences

GRAPHICS IN MIDP

Class Hierarchy

javax.microedition.lcduijavax.microedition.lcdui javax.microedition.lcdui.gamejavax.microedition.lcdui.game

DisplayableDisplayable

AlertAlert ListList FormForm TextBoxTextBox

ScreenScreen

CanvasCanvas GameCanvasGameCanvas

Using Graphics

• Class: javax.microedition.lcdui.Canvas• Create a subclass:

– class MyCanvas extends Canvas

• Canvas-class has only one abstract method:– paint(graphics g)

• It is possible to override methods that deal with events

Simple Exampleclass MyCanvas extends Canvas{

public void paint(Graphics g){// draw

}

}

class MyMidlet extends MIDlet{

public void startApp(){MyCanvas mycanvas = new MyCanvas();

Display.getDisplay(this).setCurrent(mycanvas);

}

}

Repainting

• You never call the paint() method.• Instead of you use repaint():

– By using this method, you ask the framework to repaint the canvas

– Framework decides when is the best time to repaint the canvas

• There is a also:– repaint(int x, int y, int width, int height)

Coordinates

• Upper-Left (0,0)• Translate the origon

– translate() – metodi

• Origo's position:– getTranslateX()– getTranslateY()

x

y

Graphics-classes drawing methods

• See the API!– drawLine(..)– drawRect(...)– drawRoundRect(...)– drawArc(...)– fillTriangle(...)– fillRect(...)– fillRoundRect(...)– fillArc(...)

Graphics-classes Color related methods

• public void setColor(int r, int g, int b)

• int getColor()

• int getRedComponent()

• int getBlueComponent()

• int getGreenComponent()

• isColor()

• numColors()

Line types

• setStrokeStyle(Graphics.DOTTED)• setStrokeStyle(Graphics.SOLID)

Drawing text

• public void drawString(String str, int x, int y, int anchor)

• What is anchor?

HeipodeiTOP|LEFT

TOP|HCENTERTOP|RIGHT

BASELINE|RIGHT

BOTTOM|RIGHTBOTTOM | HCENTER

BASELINE | HCENTER

BASELINE|LEFT

BOTTOM | LEFT

Fonts

• Types– Font.FACE_PROPORTIONAL– Font.FACE_MONOSPACE– Font.FACE_SYSTEM

• Styles– Font.STYLE_PLAIN– Font.STYLE_BOLD– Font.STYLE_ITALIC– Font.STYLE_UNDERLINE

• Sizes– Font.SIZE_SMALL– Font.SIZE_MEDIUM– Font.SIZE_LARGE

Using Font

• Font f = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_ITALIC, Font.SIZE_SMALL);

• g.setFont(f);• g.drawString(”Hello”, 0,0, Graphics.TOP |

Graphics.LEFT);

Measuring text

• public int charWidth(char c)

• public int charsWidth(char ch, int offset, int length)

• public int stringWidth(String str)

• public int substringWidth(String str, int offset, int len)

Pictures

• MIDP Specification supports atleast png-format• You can put the pictures in the res-folder

– => .jar

• Methods– static Image createImage(String name) (Image-class)

– void drawImage(Image img, int x, int y, int anchor) (Graphics-class)

Picture's anchorsTOP | HCENTERTOP | LEFT

VCENTER | LEFT

BOTTOM | LEFT BOTTOM | HCENTER BOTTOM | RIGHT

VCENTER | RIGHT

TOP | RIGHT

VCENTER | HCENTER

Event handling• Canvas-class

– protected void keyPressed(int keyCode)– protected void keyReleased(int keyCode)– protected void keyRepeated(int keyCode) – protected void pointerPressed(int x, int y)– protected void pointerReleased(int x, int y)– protected void pointerDragged(int x, int y)

Example: Using Graphics

THREADS

What are threads?

• Multithreading.. – Methods that are running at the same time– For example: downloading, checking and

analyzing is happening in a program at the same time.

• In Java:– An instance of class java.lang.Thread

JVM and Threads

• JVM is responsible scheduling the threads• Sometimes native OS's thread system is

used... and sometimes it is not.– When it comes to threads, very little is

guaranteed.

• Different JVMs run threads in a different way!

Making a thread

• A thread begins as an instance of java-lang.Thread

• Thread class has following methods (among others)– start()– yield()– sleep()– run()

run-method

• This is the method that you want to be executed in a separed thread

• public void run(){– You job code goes to here

• }

• Where does the run() method go?• Two choices

– 1) Extend the java.lang.Thread class– 2) Implement the Runnable interface

1) Extending java.lang.Thread

• The simplest way to define code to run in a separate thread is to– Extend the Thread class– Override the run() method

class MyThread extends Thread{

public void run(){

System.out.println("Job running in thread");

}

}

2) Implementing java.lang.Runnable

• Implement the Runnable interfaceclass MyRunnable implements Runnable{

public void run(){

System.out.println("Job running in Thread");

}

}

Two choices..

• Why two choices?• Use choice 1 (extending Thread) if possible..

(thread is easier to start)• If your class extends already some other class,

use choice 2 (implement Runnable)

Instantiating a Thread

• Every thread of execution begins as an instance of class Thread.

• If you extended the Thread-class:– MyThread t = new MyThread();

• If you implemented Runnable:– MyRunnable r = new MyRunnable();

Thread t = new Thread(r);

Starting a Thread

• Once the Thread is created, you have to start it.• Starting the thread is done by using start()-method:

– t.start();

• What happens after you call start()?– A new thread of execution starts– The thread moves from new state to runnable state.– When the thread gets a chance to execute, its target run()

method will run.

Choice 1 (Extending Thread)class FooThread extends Thread{

public void run(){for(int x=1; x<6; x++){

System.out.println("runnable running!");}

}}class Test{

public static void main(String [] args){FooThread foo = new FooThread();foo.start();

}}

Choice 2 (implement Runnable)class FooRunnable extends SomeOtherClass implements Runnable{

public void run(){for(int x=1; x<6; x++){

System.out.println("runnable running!");}

}}class Test{

public static void main(String [] args){FooRunnable foo = new FooRunnable();Thread t = new Thread(foo);t.start();

}}

Thread States

New Runnable Running Dead

Waiting/Blocking/Sleeping

Preventing Thread Execution: Sleep

• Sleep() method is a static method of class Thread

• Exampleclass NameRunnable implements Runnable{

public void run(){for(int i=0; i<5; i++){

System.out.println("thread");try{Thread.sleep(6*1000); // Sleep 6 seconds}catch(InterruptedException ex){}

}}

}

Easiest way to do threads in midlets

class MyMidlet extends Midlet implements Runnable {public MyMidlet() {

Thread x = new Thread(this);x.start();

}public void run() {

}}

Example: Midlets and threads

HTTP CONNECTION IN MIDP

Basic Architecture

Internet MIDPDevice

Web Server

User requests information from an Application (e.g. MyServlet)

Web server passes output from MyServlet back to the MIDlet

Web Server launches MyServlet program and sends it parameters the MIDlet requested

Web Server retrieves output fromthe MyServlet

HttpConnection

• Request-response application protocol• Parameters of request must be set before the request is sent• Connection states:

– Setup– Connected– Closed

• Setup state methods:– setRequestMethod (POST or GET)– setRequestProperty– With these methods you can cover the HTTP headers that are typically seen in

an HTTP request

What is needed ?

• MIDlet & MIDP Device• Servlet & Web Server• Connection between MIDP Device & Web

Server• Common Protocol between MIDlet and

Servlet

Using HTTP Connection

HttpConnection hc = (HttpConnection)Connector.open(URL);DataInputStream in = new DataInputStream(hc.openInputStream());int ch;String alltext = new String("");while ((ch = in.read()) != -1)

alltext += ((char) ch);hc.close();in.close();

Example: Midlet and HTTP-Connection

top related