Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Threads Advantages some tasks inherently parallel – can exploit the underlying architecture responsive applications – user can still use application while operation pending sharing of resources (communication) is easier switching between threads is faster than process switching overhead in creating threads is small
Threads Single-threaded process Global DataFiles, I/O RegistersStack thread Multi-threaded process Global DataFiles, I/O Registers Stack Registers Stack Registers Stack
Java thread States newrunnabledead blocked new start() exits run() method wait for I/O (file, input) I/O available
Creating Threads Extend the Thread class, override run() method class FetchThread extends Thread { private String url; public FetchThread(String url) { this.url = url; } public void run() { // 1. connect to server // 2. download page // 3. update view widget } // LATER ON... Thread fetch = new FetchThread(“ fetch.start();
Creating Threads Implement Runnable interface (only one method run()) class FetchThread implements Runnable { private String url; public FetchThread(String url) { this.url = url; } public void run() { // 1. connect to server // 2. download page // 3. update view widget } // LATER ON... Runnable target = new FetchThread(“ Thread fetch = new Thread(target); fetch.start();
MIDlets and Threads (I) class DemoMIDlet implements CommandListener, Runnable { public void run() { if (lastCmd == addCmd) { // handle add operation } else if (lastCmd == showCmd) { // handle show operation } public void commandAction(Command c, Displayable d) { Form ackForm = new Form(“Working...”); display.setCurrent(ackForm); Thread t = new Thread(this); t.start(); }
MIDlets and Threads (II) class DemoMIDlet implements CommandListener, Runnable { class UpdateThread implements Runnable { Command lastCmd; public void UpdateThread(Command c) { lastCmd = c; } public void run() { if (lastCmd == addCmd) { // handle add operation } public void commandAction(Command c, Displayable d) { Form ackForm = new Form(“Working...”); display.setCurrent(ackForm); Thread t = new Thread(new UpdateThread(c)); t.start(); }
Demo
Taking Pictures Setting up the Control player = Manager.createPlayer("capture://video"); player.realize(); videoControl = (VideoControl) player.getControl("VideoControl"); Form form = new Form("Camera Form"); Item item = (Item) videoControl.initDisplayMode( GUIControl.USE_GUI_PRIMITIVE, null); form.append(item); mDisplay.setCurrent(form); Taking the picture byte[] raw = videoControl.getSnapshot(null); Image image = Image.createImage(raw, 0, raw.length);
Taking Pictures Permissions javax.microedition.media.control.RecordControl javax.microedition.media.control.VideoControl.getSnapshot