2 * Copyright 2007 Google Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.client.j2me;
19 import com.google.zxing.MonochromeBitmapSource;
20 import com.google.zxing.MultiFormatReader;
21 import com.google.zxing.Reader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
25 import javax.microedition.lcdui.Image;
26 import javax.microedition.media.MediaException;
27 import javax.microedition.media.Player;
28 import javax.microedition.media.control.VideoControl;
31 * @author Sean Owen (srowen@google.com)
33 final class SnapshotThread extends Thread {
35 private static SnapshotThread currentThread;
37 private final ZXingMIDlet zXingMIDlet;
39 private SnapshotThread(ZXingMIDlet zXingMIDlet) {
40 this.zXingMIDlet = zXingMIDlet;
43 static synchronized void startThread(ZXingMIDlet zXingMIDlet) {
44 if (currentThread == null) {
45 currentThread = new SnapshotThread(zXingMIDlet);
46 currentThread.start();
51 Player player = zXingMIDlet.getPlayer();
53 AdvancedMultimediaManager.setFocus(player);
56 } catch (MediaException me) {
59 byte[] snapshot = takeSnapshot();
60 Image capturedImage = Image.createImage(snapshot, 0, snapshot.length);
61 MonochromeBitmapSource source = new LCDUIImageMonochromeBitmapSource(capturedImage);
62 Reader reader = new MultiFormatReader();
63 Result result = reader.decode(source);
64 zXingMIDlet.handleDecodedText(result.getText());
65 } catch (ReaderException re) {
66 // Show a friendlier message on a mere failure to read the barcode
67 zXingMIDlet.showError("Sorry, no barcode was found.");
68 } catch (MediaException me) {
69 zXingMIDlet.showError(me);
70 } catch (RuntimeException re) {
71 zXingMIDlet.showError(re);
75 } catch (MediaException me) {
83 private byte[] takeSnapshot() throws MediaException {
84 VideoControl videoControl = zXingMIDlet.getVideoControl();
85 byte[] snapshot = null;
87 snapshot = videoControl.getSnapshot(null);
88 } catch (MediaException me) {
90 if (snapshot == null) {
91 // Fall back on JPEG; seems that some cameras default to PNG even
92 // when PNG isn't supported!
93 snapshot = videoControl.getSnapshot("encoding=jpeg");
94 if (snapshot == null) {
95 throw new MediaException("Can't obtain a snapshot");