Remove progress dialog to avoid rare exception
[zxing.git] / android / src / com / google / zxing / client / android / encode / EncodeActivity.java
1 /*
2  * Copyright (C) 2008 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.android.encode;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.WriterException;
21 import com.google.zxing.client.android.FinishListener;
22 import com.google.zxing.client.android.Intents;
23 import com.google.zxing.client.android.R;
24
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.content.Intent;
28 import android.graphics.Bitmap;
29 import android.net.Uri;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.Environment;
33 import android.os.Message;
34 import android.util.Log;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
39 import android.widget.ImageView;
40 import android.widget.TextView;
41
42 import java.io.File;
43 import java.io.FileNotFoundException;
44 import java.io.FileOutputStream;
45 import java.io.IOException;
46
47 /**
48  * This class encodes data from an Intent into a QR code, and then displays it full screen so that
49  * another person can scan it with their device.
50  *
51  * @author dswitkin@google.com (Daniel Switkin)
52  */
53 public final class EncodeActivity extends Activity {
54
55   private static final String TAG = EncodeActivity.class.getSimpleName();
56
57   private static final int SHARE_BARCODE_DIMENSION = 300;
58   private static final int MAX_BARCODE_FILENAME_LENGTH = 24;
59
60   private QRCodeEncoder qrCodeEncoder;
61   private boolean firstLayout;
62
63   /**
64    * This needs to be delayed until after the first layout so that the view dimensions will be
65    * available.
66    */
67   private final OnGlobalLayoutListener layoutListener = new OnGlobalLayoutListener() {
68     public void onGlobalLayout() {
69       if (firstLayout) {
70         View layout = findViewById(R.id.encode_view);
71         int width = layout.getWidth();
72         int height = layout.getHeight();
73         int smallerDimension = width < height ? width : height;
74         smallerDimension = smallerDimension * 7 / 8;
75
76         Intent intent = getIntent();
77         try {
78           qrCodeEncoder = new QRCodeEncoder(EncodeActivity.this, intent);
79           setTitle(getString(R.string.app_name) + " - " + qrCodeEncoder.getTitle());
80           qrCodeEncoder.requestBarcode(handler, smallerDimension);
81         } catch (IllegalArgumentException e) {
82           showErrorMessage(R.string.msg_encode_contents_failed);
83         }
84         firstLayout = false;
85       }
86     }
87   };
88
89   private final Handler handler = new Handler() {
90     @Override
91     public void handleMessage(Message message) {
92       switch (message.what) {
93         case R.id.encode_succeeded:
94           Bitmap image = (Bitmap) message.obj;
95           ImageView view = (ImageView) findViewById(R.id.image_view);
96           view.setImageBitmap(image);
97           TextView contents = (TextView) findViewById(R.id.contents_text_view);
98           contents.setText(qrCodeEncoder.getDisplayContents());
99           //qrCodeEncoder = null;
100           break;
101         case R.id.encode_failed:
102           showErrorMessage(R.string.msg_encode_barcode_failed);
103           qrCodeEncoder = null;
104           break;
105       }
106     }
107   };
108
109   @Override
110   public void onCreate(Bundle icicle) {
111     super.onCreate(icicle);
112
113     Intent intent = getIntent();
114     if (intent != null) {
115       String action = intent.getAction();
116       if (action.equals(Intents.Encode.ACTION) || action.equals(Intent.ACTION_SEND)) {
117         setContentView(R.layout.encode);
118         return;
119       }
120     }
121     finish();
122   }
123
124   @Override
125   public boolean onCreateOptionsMenu(Menu menu) {
126     super.onCreateOptionsMenu(menu);
127     menu.add(0, Menu.FIRST, 0, R.string.menu_share).setIcon(android.R.drawable.ic_menu_share);
128     return true;
129   }
130
131   @Override
132   public boolean onOptionsItemSelected(MenuItem item) {
133     if (qrCodeEncoder == null) { // Odd
134       Log.w(TAG, "No existing barcode to send?");
135       return true;
136     }
137
138     String contents = qrCodeEncoder.getContents();
139     Bitmap bitmap;
140     try {
141       bitmap = QRCodeEncoder.encodeAsBitmap(contents, BarcodeFormat.QR_CODE,
142           SHARE_BARCODE_DIMENSION, SHARE_BARCODE_DIMENSION);
143     } catch (WriterException we) {
144       Log.w(TAG, we);
145       return true;
146     }
147
148     File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner");
149     File barcodesRoot = new File(bsRoot, "Barcodes");
150     if (!barcodesRoot.exists() && !barcodesRoot.mkdirs()) {
151       Log.w(TAG, "Couldn't make dir " + barcodesRoot);
152       showErrorMessage(R.string.msg_unmount_usb);
153       return true;
154     }
155     File barcodeFile = new File(barcodesRoot, makeBarcodeFileName(contents) + ".png");
156     barcodeFile.delete();
157     FileOutputStream fos = null;
158     try {
159       fos = new FileOutputStream(barcodeFile);
160       bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
161     } catch (FileNotFoundException fnfe) {
162       Log.w(TAG, "Couldn't access file " + barcodeFile + " due to " + fnfe);
163       showErrorMessage(R.string.msg_unmount_usb);
164       return true;
165     } finally {
166       if (fos != null) {
167         try {
168           fos.close();
169         } catch (IOException ioe) {
170           // do nothing
171         }
172       }
173     }
174
175     Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
176     intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - " +
177         qrCodeEncoder.getTitle());
178     intent.putExtra(Intent.EXTRA_TEXT, qrCodeEncoder.getContents());
179     intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath()));
180     intent.setType("image/png");
181     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
182     startActivity(Intent.createChooser(intent, null));
183     return true;
184   }
185
186   private static CharSequence makeBarcodeFileName(CharSequence contents) {
187     int fileNameLength = Math.min(MAX_BARCODE_FILENAME_LENGTH, contents.length());
188     StringBuilder fileName = new StringBuilder(fileNameLength);
189     for (int i = 0; i < fileNameLength; i++) {
190       char c = contents.charAt(i);
191       if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
192         fileName.append(c);
193       } else {
194         fileName.append('_');
195       }
196     }
197     return fileName;
198   }
199
200   @Override
201   protected void onResume() {
202     super.onResume();
203     View layout = findViewById(R.id.encode_view);
204     layout.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
205     firstLayout = true;
206   }
207
208   private void showErrorMessage(int message) {
209     AlertDialog.Builder builder = new AlertDialog.Builder(this);
210     builder.setMessage(message);
211     builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
212     builder.setOnCancelListener(new FinishListener(this));
213     builder.show();
214   }
215 }