Issue 131: reuse Alert objects
[zxing.git] / javame / src / com / google / zxing / client / j2me / ZXingMIDlet.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.j2me;
18
19 import com.google.zxing.Result;
20 import com.google.zxing.client.result.EmailAddressParsedResult;
21 import com.google.zxing.client.result.ParsedResult;
22 import com.google.zxing.client.result.ParsedResultType;
23 import com.google.zxing.client.result.ResultParser;
24 import com.google.zxing.client.result.SMSParsedResult;
25 import com.google.zxing.client.result.TelParsedResult;
26 import com.google.zxing.client.result.ProductParsedResult;
27 import com.google.zxing.client.result.URIParsedResult;
28
29 import javax.microedition.io.ConnectionNotFoundException;
30 import javax.microedition.lcdui.Alert;
31 import javax.microedition.lcdui.AlertType;
32 import javax.microedition.lcdui.Canvas;
33 import javax.microedition.lcdui.Command;
34 import javax.microedition.lcdui.CommandListener;
35 import javax.microedition.lcdui.Display;
36 import javax.microedition.lcdui.Displayable;
37 import javax.microedition.media.Manager;
38 import javax.microedition.media.MediaException;
39 import javax.microedition.media.Player;
40 import javax.microedition.media.control.VideoControl;
41 import javax.microedition.midlet.MIDlet;
42 import javax.microedition.midlet.MIDletStateChangeException;
43 import java.io.IOException;
44
45 /**
46  * <p>The actual reader application {@link MIDlet}.</p>
47  *
48  * @author Sean Owen
49  */
50 public final class ZXingMIDlet extends MIDlet {
51
52   private static final int ALERT_TIMEOUT_MS = 5 * 1000;
53
54   private Canvas canvas;
55   private Player player;
56   private VideoControl videoControl;
57   private Alert confirmation;
58   private Alert alert;
59
60   Displayable getCanvas() {
61     return canvas;
62   }
63
64   Player getPlayer() {
65     return player;
66   }
67
68   VideoControl getVideoControl() {
69     return videoControl;
70   }
71
72   static MultimediaManager buildMultimediaManager() {
73     return new AdvancedMultimediaManager();
74     // Comment line above / uncomment below to make the basic version
75     // return new DefaultMultimediaManager();
76   }
77
78   protected void startApp() throws MIDletStateChangeException {
79     try {
80       player = createPlayer();
81       player.realize();
82       MultimediaManager multimediaManager = buildMultimediaManager();
83       multimediaManager.setZoom(player);
84       multimediaManager.setExposure(player);
85       videoControl = (VideoControl) player.getControl("VideoControl");
86       canvas = new VideoCanvas(this);
87       canvas.setFullScreenMode(true);
88       videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, canvas);
89       videoControl.setDisplayLocation(0, 0);
90       videoControl.setDisplaySize(canvas.getWidth(), canvas.getHeight());
91       videoControl.setVisible(true);
92       player.start();
93       Display.getDisplay(this).setCurrent(canvas);
94     } catch (IOException ioe) {
95       throw new MIDletStateChangeException(ioe.toString());
96     } catch (MediaException me) {
97       throw new MIDletStateChangeException(me.toString());
98     }
99
100     // Set up one confirmation and alert object to re-use
101     confirmation = new Alert(null);
102     confirmation.setType(AlertType.CONFIRMATION);
103     confirmation.setTimeout(ALERT_TIMEOUT_MS);
104     Command yes = new Command("Yes", Command.OK, 1);
105     confirmation.addCommand(yes);
106     Command no = new Command("No", Command.CANCEL, 1);
107     confirmation.addCommand(no);
108     alert = new Alert(null);
109     alert.setTimeout(ALERT_TIMEOUT_MS);
110   }
111
112   private static Player createPlayer() throws IOException, MediaException {
113     // Try a workaround for Nokias, which want to use capture://image in some cases
114     Player player = null;
115     String platform = System.getProperty("microedition.platform");
116     if (platform != null && platform.indexOf("Nokia") >= 0) {
117       try {
118         player = Manager.createPlayer("capture://image");
119       } catch (MediaException me) {
120         // if this fails, just continue with capture://video
121       } catch (Error e) {
122         // Ugly, but, it seems the Nokia N70 throws "java.lang.Error: 136" here
123         // We should still try to continue
124       }
125     }
126     if (player == null) {
127       player = Manager.createPlayer("capture://video");
128     }
129     return player;
130   }
131
132   protected void pauseApp() {
133     if (player != null) {
134       try {
135         player.stop();
136       } catch (MediaException me) {
137         // continue?
138         showError(me);
139       }
140     }
141   }
142
143   protected void destroyApp(boolean unconditional) {
144     if (player != null) {
145       videoControl = null;
146       try {
147         player.stop();
148       } catch (MediaException me) {
149         // continue
150       }
151       player.deallocate();
152       player.close();
153       player = null;
154     }
155   }
156
157   void stop() {
158     destroyApp(false);
159     notifyDestroyed();
160   }
161
162   // Convenience methods to show dialogs
163
164   private void showOpenURL(String title, String display, final String uri) {
165     confirmation.setTitle(title);
166     confirmation.setString(display);
167     CommandListener listener = new CommandListener() {
168       public void commandAction(Command command, Displayable displayable) {
169         if (command.getCommandType() == Command.OK) {
170           try {
171             platformRequest(uri);
172           } catch (ConnectionNotFoundException cnfe) {
173             showError(cnfe);
174           } finally {
175             stop();
176           }
177         } else {
178           // cancel
179           Display.getDisplay(ZXingMIDlet.this).setCurrent(getCanvas());
180         }
181       }
182     };
183     confirmation.setCommandListener(listener);
184     showAlert(confirmation);
185   }
186
187   private void showAlert(String title, String text) {
188     alert.setTitle(title);
189     alert.setString(text);
190     alert.setType(AlertType.INFO);
191     showAlert(alert);
192   }
193
194   void showError(Throwable t) {
195     String message = t.getMessage();
196     if (message != null && message.length() > 0) {
197       showError(message);
198     } else {
199       showError(t.toString());
200     }
201   }
202
203   void showError(String message) {
204     alert.setTitle("Error");
205     alert.setString(message);
206     alert.setType(AlertType.ERROR);
207     showAlert(alert);
208   }
209
210   private void showAlert(Alert alert) {
211     Display display = Display.getDisplay(this);
212     display.setCurrent(alert, canvas);
213   }
214
215   void handleDecodedText(Result theResult) {
216     ParsedResult result = ResultParser.parseResult(theResult);
217     ParsedResultType type = result.getType();
218     if (type.equals(ParsedResultType.URI)) {
219       String uri = ((URIParsedResult) result).getURI();
220       showOpenURL("Open Web Page?", uri, uri);
221     } else if (type.equals(ParsedResultType.EMAIL_ADDRESS)) {
222       EmailAddressParsedResult emailResult = (EmailAddressParsedResult) result;
223       showOpenURL("Compose E-mail?", emailResult.getEmailAddress(), emailResult.getMailtoURI());
224     } else if (type.equals(ParsedResultType.SMS)) {
225       SMSParsedResult smsResult = (SMSParsedResult) result;
226       showOpenURL("Compose SMS?", smsResult.getNumber(), smsResult.getSMSURI());
227     } else if (type.equals(ParsedResultType.PRODUCT)) {
228       ProductParsedResult productResult = (ProductParsedResult) result;
229       String uri = "http://www.upcdatabase.com/item.asp?upc=" + productResult.getNormalizedProductID();
230       showOpenURL("Look Up Barcode Online?", productResult.getProductID(), uri);
231     } else if (type.equals(ParsedResultType.TEL)) {
232       TelParsedResult telResult = (TelParsedResult) result;
233       showOpenURL("Dial Number?", telResult.getNumber(), telResult.getTelURI());
234     } else {
235       showAlert("Barcode Detected", result.getDisplayResult());
236     }
237   }
238
239 }