1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.ImageView;
import android.widget.ZoomButtonsController;
import com.android.camera.gallery.IImage;
import com.android.camera.gallery.IImageList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Activity of the Camera which used to see preview and take pictures.
*/
public class Camera extends Activity implements View.OnClickListener,
ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
Switcher.OnSwitchListener, FlashButton.ModeChangeListener,
OnSharedPreferenceChangeListener {
private static final String TAG = "camera";
private static final int CROP_MSG = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int RESTART_PREVIEW = 3;
private static final int CLEAR_SCREEN_DELAY = 4;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private static final int FOCUS_BEEP_VOLUME = 100;
private double mZoomValue; // The current zoom value.
private boolean mZooming = false;
private double mZoomStep;
private double mZoomMax;
public static final double ZOOM_STEP_MIN = 0.25;
public static final String ZOOM_STOP = "stop";
public static final String ZOOM_IMMEDIATE = "zoom-immediate";
public static final String ZOOM_CONTINUOUS = "zoom-continuous";
public static final double ZOOM_MIN = 1.0;
public static final String ZOOM_SPEED = "99";
private Parameters mParameters;
// The parameter strings to communicate with camera driver.
public static final String PARM_ZOOM_STATE = "zoom-state";
public static final String PARM_ZOOM_STEP = "zoom-step";
public static final String PARM_ZOOM_TO_LEVEL = "zoom-to-level";
public static final String PARM_ZOOM_SPEED = "zoom-speed";
public static final String PARM_ZOOM_MAX = "max-picture-continuous-zoom";
private OrientationEventListener mOrientationListener;
private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private SharedPreferences mPreferences;
private static final int IDLE = 1;
private static final int SNAPSHOT_IN_PROGRESS = 2;
private static final boolean SWITCH_CAMERA = true;
private static final boolean SWITCH_VIDEO = false;
private int mStatus = IDLE;
private static final String sTempCropFilename = "crop-temp";
private android.hardware.Camera mCameraDevice;
private VideoPreview mSurfaceView;
private SurfaceHolder mSurfaceHolder = null;
private ShutterButton mShutterButton;
private FocusRectangle mFocusRectangle;
private FlashButton mFlashButton;
private ImageView mGpsIndicator;
private ToneGenerator mFocusToneGenerator;
private ZoomButtonsController mZoomButtons;
private GestureDetector mGestureDetector;
private Switcher mSwitcher;
private boolean mStartPreviewFail = false;
// mPostCaptureAlert, mLastPictureButton, mThumbController
// are non-null only if isImageCaptureIntent() is true.
private ImageView mLastPictureButton;
private ThumbnailController mThumbController;
private int mViewFinderWidth, mViewFinderHeight;
private ImageCapture mImageCapture = null;
private boolean mPreviewing;
private boolean mPausing;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private boolean mRecordLocation;
private static final int FOCUS_NOT_STARTED = 0;
private static final int FOCUSING = 1;
private static final int FOCUSING_SNAP_ON_FINISH = 2;
private static final int FOCUS_SUCCESS = 3;
private static final int FOCUS_FAIL = 4;
private int mFocusState = FOCUS_NOT_STARTED;
private ContentResolver mContentResolver;
private boolean mDidRegister = false;
private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
private LocationManager mLocationManager = null;
// Use OneShotPreviewCallback to measure the time between
// JpegPictureCallback and preview.
private final OneShotPreviewCallback mOneShotPreviewCallback =
new OneShotPreviewCallback();
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final ZoomCallback mZoomCallback = new ZoomCallback();
// Use the ErrorCallback to capture the crash count
// on the mediaserver
private final ErrorCallback mErrorCallback = new ErrorCallback();
private long mFocusStartTime;
private long mFocusCallbackTime;
private long mCaptureStartTime;
private long mShutterCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private int mPicturesRemaining;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterAndRawPictureCallbackTime;
public long mJpegPictureCallbackTimeLag;
public long mRawPictureAndJpegPictureCallbackTime;
// Add the media server tag
public static boolean mMediaServerDied = false;
// Focus mode. Options are pref_camera_focusmode_entryvalues.
private String mFocusMode;
private final Handler mHandler = new MainHandler();
private OnScreenSettings mSettings;
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RESTART_PREVIEW: {
restartPreview();
break;
}
case CLEAR_SCREEN_DELAY: {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
}
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Create orientation listenter. This should be done first because it
// takes some time to get first orientation.
mOrientationListener =
new OrientationEventListener(Camera.this) {
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user
// first orient the camera then point the camera to
// floor/sky, we still have the correct orientation.
if (orientation != ORIENTATION_UNKNOWN) {
mLastOrientation = orientation;
}
}
};
mOrientationListener.enable();
// Initialize location sevice.
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
readPreference();
if (mRecordLocation) startReceivingLocationUpdates();
checkStorage();
// Initialize last picture button.
mContentResolver = getContentResolver();
if (!mIsImageCaptureIntent) {
findViewById(R.id.camera_switch).setOnClickListener(this);
mLastPictureButton =
(ImageView) findViewById(R.id.review_thumbnail);
mLastPictureButton.setOnClickListener(this);
mThumbController = new ThumbnailController(
getResources(), mLastPictureButton, mContentResolver);
mThumbController.loadData(ImageManager.getLastImageThumbPath());
// Update last image thumbnail.
updateThumbnailButton();
}
// Initialize shutter button.
mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
updateFocusIndicator();
// Initialize flash button
if (mParameters.getSupportedFlashModes() != null) {
mFlashButton = (FlashButton) findViewById(R.id.flash_button);
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE, "auto");
mFlashButton.setMode(flashMode);
mFlashButton.setVisibility(View.VISIBLE);
mFlashButton.setListener(this);
}
// Initialize GPS indicator.
mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator);
mGpsIndicator.setImageResource(R.drawable.ic_camera_sym_gps);
ImageManager.ensureOSXCompatibleFolder();
installIntentFilter();
initializeFocusTone();
initializeZoom();
mFirstTimeInitialized = true;
}
private void updateThumbnailButton() {
// Update last image if URI is invalid and the storage is ready.
if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
updateLastImage();
}
mThumbController.updateDisplayIfNeeded();
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start orientation listener as soon as possible because it takes
// some time to get first orientation.
mOrientationListener.enable();
// Start location update if needed.
readPreference();
if (mRecordLocation) startReceivingLocationUpdates();
installIntentFilter();
initializeFocusTone();
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
private void initializeZoom() {
// Check if the phone has zoom capability.
String zoomState = mParameters.get(PARM_ZOOM_STATE);
if (zoomState == null) return;
mZoomValue = Double.parseDouble(mParameters.get(PARM_ZOOM_TO_LEVEL));
mZoomMax = Double.parseDouble(mParameters.get(PARM_ZOOM_MAX));
mZoomStep = Double.parseDouble(mParameters.get(PARM_ZOOM_STEP));
mParameters.set(PARM_ZOOM_SPEED, ZOOM_SPEED);
mCameraDevice.setParameters(mParameters);
mGestureDetector = new GestureDetector(this, new ZoomGestureListener());
mCameraDevice.setZoomCallback(mZoomCallback);
mZoomButtons = new ZoomButtonsController(mSurfaceView);
mZoomButtons.setAutoDismissed(true);
mZoomButtons.setZoomSpeed(100);
mZoomButtons.setOnZoomListener(
new ZoomButtonsController.OnZoomListener() {
public void onVisibilityChanged(boolean visible) {
if (visible) {
updateZoomButtonsEnabled();
}
}
public void onZoom(boolean zoomIn) {
if (mZooming) return;
if (zoomIn) {
if (mZoomValue < mZoomMax) {
mZoomValue += mZoomStep;
zoomToLevel(ZOOM_CONTINUOUS);
}
} else {
if (mZoomValue > ZOOM_MIN) {
mZoomValue -= mZoomStep;
zoomToLevel(ZOOM_CONTINUOUS);
}
}
updateZoomButtonsEnabled();
}
});
}
private void zoomToLevel(String type) {
if (type == null) {
Log.e(TAG, "Zoom type is null.");
return;
}
if (mZoomValue > mZoomMax) mZoomValue = mZoomMax;
if (mZoomValue < ZOOM_MIN) mZoomValue = ZOOM_MIN;
// If the application sets a unchanged zoom value, the driver will stuck
// at the zoom state. This is a work-around to ensure the state is at
// "stop".
mParameters.set(PARM_ZOOM_STATE, ZOOM_STOP);
mCameraDevice.setParameters(mParameters);
mParameters.set(PARM_ZOOM_TO_LEVEL, Double.toString(mZoomValue));
mParameters.set(PARM_ZOOM_STATE, type);
mCameraDevice.setParameters(mParameters);
if (ZOOM_CONTINUOUS.equals(type)) mZooming = true;
}
private void updateZoomButtonsEnabled() {
mZoomButtons.setZoomInEnabled(mZoomValue < mZoomMax);
mZoomButtons.setZoomOutEnabled(mZoomValue > ZOOM_MIN);
}
private class ZoomGestureListener extends
GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
// Show zoom buttons only when preview is started and snapshot
// is not in progress. mZoomButtons may be null if it is not
// initialized.
if (!mPausing && isCameraIdle() && mPreviewing
&& mZoomButtons != null) {
mZoomButtons.setVisible(true);
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
// Perform zoom only when preview is started and snapshot is not in
// progress.
if (mPausing || !isCameraIdle() || !mPreviewing
|| mZoomButtons == null || mZooming) {
return false;
}
if (mZoomValue < mZoomMax) {
// Zoom in to the maximum.
while (mZoomValue < mZoomMax) {
mZoomValue += ZOOM_STEP_MIN;
zoomToLevel(ZOOM_IMMEDIATE);
// Wait for a while so we are not changing zoom too fast.
try {
Thread.currentThread().sleep(5);
} catch (InterruptedException ex) {
}
}
} else {
// Zoom out to the minimum.
while (mZoomValue > ZOOM_MIN) {
mZoomValue -= ZOOM_STEP_MIN;
zoomToLevel(ZOOM_IMMEDIATE);
// Wait for a while so we are not changing zoom too fast.
try {
Thread.currentThread().sleep(5);
} catch (InterruptedException ex) {
}
}
}
updateZoomButtonsEnabled();
return true;
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
return mGestureDetector.onTouchEvent(m);
}
return true;
}
LocationListener [] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING)
|| action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
checkStorage();
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
}
};
private class LocationListener
implements android.location.LocationListener {
Location mLastLocation;
boolean mValid = false;
String mProvider;
public LocationListener(String provider) {
mProvider = provider;
mLastLocation = new Location(mProvider);
}
public void onLocationChanged(Location newLocation) {
if (newLocation.getLatitude() == 0.0
&& newLocation.getLongitude() == 0.0) {
// Hack to filter out 0.0,0.0 locations
return;
}
// If GPS is available before start camera, we won't get status
// update so update GPS indicator when we receive data.
if (mRecordLocation
&& LocationManager.GPS_PROVIDER.equals(mProvider)) {
mGpsIndicator.setVisibility(View.VISIBLE);
}
mLastLocation.set(newLocation);
mValid = true;
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
mValid = false;
}
public void onStatusChanged(
String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE: {
mValid = false;
if (mRecordLocation &&
LocationManager.GPS_PROVIDER.equals(provider)) {
mGpsIndicator.setVisibility(View.INVISIBLE);
}
break;
}
}
}
public Location current() {
return mValid ? mLastLocation : null;
}
}
private final class OneShotPreviewCallback
implements android.hardware.Camera.PreviewCallback {
public void onPreviewFrame(byte[] data,
android.hardware.Camera camera) {
long now = System.currentTimeMillis();
if (mJpegPictureCallbackTime != 0) {
mJpegPictureCallbackTimeLag = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegPictureCallbackTimeLag = "
+ mJpegPictureCallbackTimeLag + "ms");
mJpegPictureCallbackTime = 0;
} else {
Log.v(TAG, "Got first frame");
}
}
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
clearFocusState();
}
}
private final class RawPictureCallback implements PictureCallback {
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
mShutterAndRawPictureCallbackTime =
mRawPictureCallbackTime - mShutterCallbackTime;
Log.v(TAG, "mShutterAndRawPictureCallbackTime = "
+ mShutterAndRawPictureCallbackTime + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPausing) {
return;
}
mJpegPictureCallbackTime = System.currentTimeMillis();
mRawPictureAndJpegPictureCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
Log.v(TAG, "mRawPictureAndJpegPictureCallbackTime = "
+ mRawPictureAndJpegPictureCallbackTime + "ms");
mImageCapture.storeImage(jpegData, camera, mLocation);
if (!mIsImageCaptureIntent) {
long delay = 1200 - (
System.currentTimeMillis() - mRawPictureCallbackTime);
mHandler.sendEmptyMessageDelayed(
RESTART_PREVIEW, Math.max(delay, 0));
}
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
mFocusCallbackTime = System.currentTimeMillis();
mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
// Take the picture no matter focus succeeds or fails. No need
// to play the AF sound if we're about to play the shutter
// sound.
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
mImageCapture.onSnap();
} else if (mFocusState == FOCUSING) {
// User is half-pressing the focus key. Play the focus tone.
// Do not take the picture now.
ToneGenerator tg = mFocusToneGenerator;
if (tg != null) {
tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
}
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
} else if (mFocusState == FOCUS_NOT_STARTED) {
// User has released the focus key before focus completes.
// Do nothing.
}
updateFocusIndicator();
}
}
private final class ErrorCallback
implements android.hardware.Camera.ErrorCallback {
public void onError(int error, android.hardware.Camera camera) {
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
mMediaServerDied = true;
Log.v(TAG, "media server died");
}
}
}
private final class ZoomCallback
implements android.hardware.Camera.ZoomCallback {
public void onZoomUpdate(int zoomLevel,
android.hardware.Camera camera) {
mZoomValue = (double) zoomLevel / 1000;
mZooming = false;
}
}
private class ImageCapture {
private boolean mCancel = false;
private Uri mLastContentUri;
Bitmap mCaptureOnlyBitmap;
private void storeImage(byte[] data, Location loc) {
try {
long dateTaken = System.currentTimeMillis();
String name = createName(dateTaken) + ".jpg";
mLastContentUri = ImageManager.addImage(
mContentResolver,
name,
dateTaken,
loc, // location for the database goes here
0, // the dsp will use the right orientation so
// don't "double set it"
ImageManager.CAMERA_IMAGE_BUCKET_NAME,
name);
if (mLastContentUri == null) {
// this means we got an error
mCancel = true;
}
if (!mCancel) {
ImageManager.storeImage(
mLastContentUri, mContentResolver,
0, null, data);
ImageManager.setImageSize(mContentResolver, mLastContentUri,
new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
name).length());
}
} catch (Exception ex) {
Log.e(TAG, "Exception while compressing image.", ex);
}
}
public void storeImage(final byte[] data,
android.hardware.Camera camera, Location loc) {
if (!mIsImageCaptureIntent) {
storeImage(data, loc);
sendBroadcast(new Intent(
"com.android.camera.NEW_PICTURE", mLastContentUri));
setLastPictureThumb(data, mImageCapture.getLastCaptureUri());
mThumbController.updateDisplayIfNeeded();
} else {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(
data, 0, data.length, options);
showPostCaptureAlert();
}
}
/**
* Initiate the capture of an image.
*/
public void initiate() {
if (mCameraDevice == null) {
return;
}
mCancel = false;
capture();
}
public Uri getLastCaptureUri() {
return mLastContentUri;
}
public Bitmap getLastBitmap() {
return mCaptureOnlyBitmap;
}
private void capture() {
mCaptureOnlyBitmap = null;
// Set rotation.
int orientation = mLastOrientation;
if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
orientation += 90;
}
orientation = ImageManager.roundOrientation(orientation);
Log.v(TAG, "mLastOrientation = " + mLastOrientation
+ ", orientation = " + orientation);
mParameters.setRotation(orientation);
// Clear previous GPS location from the parameters.
mParameters.removeGpsData();
// Set GPS location.
Location loc = mRecordLocation ? getCurrentLocation() : null;
if (loc != null) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
if (hasLatLon) {
mParameters.setGpsLatitude(lat);
mParameters.setGpsLongitude(lon);
if (loc.hasAltitude()) {
mParameters.setGpsAltitude(loc.getAltitude());
} else {
// for NETWORK_PROVIDER location provider, we may have
// no altitude information, but the driver needs it, so
// we fake one.
mParameters.setGpsAltitude(0);
}
if (loc.getTime() != 0) {
// Location.getTime() is UTC in milliseconds.
// gps-timestamp is UTC in seconds.
long utcTimeSeconds = loc.getTime() / 1000;
mParameters.setGpsTimestamp(utcTimeSeconds);
}
} else {
loc = null;
}
}
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
new JpegPictureCallback(loc));
mPreviewing = false;
}
public void onSnap() {
// If we are already in the middle of taking a snapshot then ignore.
if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
return;
}
mCaptureStartTime = System.currentTimeMillis();
// Don't check the filesystem here, we can't afford the latency.
// Instead, check the cached value which was calculated when the
// preview was restarted.
if (mPicturesRemaining < 1) {
updateStorageHint(mPicturesRemaining);
return;
}
mStatus = SNAPSHOT_IN_PROGRESS;
mImageCapture.initiate();
}
private void clearLastBitmap() {
if (mCaptureOnlyBitmap != null) {
mCaptureOnlyBitmap.recycle();
mCaptureOnlyBitmap = null;
}
}
}
private void setLastPictureThumb(byte[] data, Uri uri) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
Bitmap lastPictureThumb =
BitmapFactory.decodeByteArray(data, 0, data.length, options);
mThumbController.setData(uri, lastPictureThumb);
}
private static String createName(long dateTaken) {
return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.camera);
mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview);
mViewFinderWidth = mSurfaceView.getLayoutParams().width;
mViewFinderHeight = mSurfaceView.getLayoutParams().height;
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPreferences.registerOnSharedPreferenceChangeListener(this);
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
Thread startPreviewThread = new Thread(new Runnable() {
public void run() {
try {
mStartPreviewFail = false;
startPreview();
} catch (CameraHardwareException e) {
// In eng build, we throw the exception so that test tool
// can detect it and report it
if ("eng".equals(Build.TYPE)) {
throw new RuntimeException(e);
}
mStartPreviewFail = true;
}
}
});
startPreviewThread.start();
// don't set mSurfaceHolder here. We have it set ONLY within
// surfaceChanged / surfaceDestroyed, other parts of the code
// assume that when it is set, the surface is also set.
SurfaceHolder holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mIsImageCaptureIntent = isImageCaptureIntent();
LayoutInflater inflater = getLayoutInflater();
ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
if (mIsImageCaptureIntent) {
View controlBar = inflater.inflate(
R.layout.attach_camera_control, rootView);
controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
} else {
inflater.inflate(R.layout.camera_control, rootView);
mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
mSwitcher.setOnSwitchListener(this);
mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
}
// Make sure preview is started.
try {
startPreviewThread.join();
if (mStartPreviewFail) {
showCameraErrorAndFinish();
return;
}
} catch (InterruptedException ex) {
// ignore
}
// Resize mVideoPreview to the right aspect ratio.
resizeForPreviewAspectRatio(mSurfaceView);
}
@Override
public void onStart() {
super.onStart();
if (!mIsImageCaptureIntent) {
mSwitcher.setSwitch(SWITCH_CAMERA);
}
}
private void checkStorage() {
if (ImageManager.isMediaScannerScanning(getContentResolver())) {
mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
} else {
calculatePicturesRemaining();
}
updateStorageHint(mPicturesRemaining);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_retake:
hidePostCaptureAlert();
restartPreview();
break;
case R.id.review_thumbnail:
if (isCameraIdle()) {
viewLastImage();
}
break;
case R.id.btn_done:
doAttach();
break;
case R.id.btn_cancel:
doCancel();
}
}
private void doAttach() {
if (mPausing) {
return;
}
Bitmap bitmap = mImageCapture.getLastBitmap();
String cropValue = null;
Uri saveUri = null;
Bundle myExtras = getIntent().getExtras();
if (myExtras != null) {
saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
cropValue = myExtras.getString("crop");
}
if (cropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to it's
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (saveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(saveUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75,
outputStream);
outputStream.close();
setResult(RESULT_OK);
finish();
} catch (IOException ex) {
// ignore exception
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
// ignore exception
}
}
}
} else {
float scale = .5F;
Matrix m = new Matrix();
m.setScale(scale, scale);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(),
bitmap.getHeight(),
m, true);
setResult(RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = openFileOutput(sTempCropFilename, 0);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
} catch (IOException ex) {
setResult(Activity.RESULT_CANCELED);
finish();
return;
} finally {
if (tempStream != null) {
try {
tempStream.close();
} catch (IOException ex) {
// ignore exception
}
}
}
Bundle newExtras = new Bundle();
if (cropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (saveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri);
} else {
newExtras.putBoolean("return-data", true);
}
Intent cropIntent = new Intent();
cropIntent.setClass(Camera.this, CropImage.class);
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
startActivityForResult(cropIntent, CROP_MSG);
}
}
private void doCancel() {
setResult(RESULT_CANCELED, new Intent());
finish();
}
public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
if (mPausing) {
return;
}
switch (button.getId()) {
case R.id.shutter_button:
doFocus(pressed);
break;
}
}
public void onShutterButtonClick(ShutterButton button) {
if (mPausing) {
return;
}
switch (button.getId()) {
case R.id.shutter_button:
doSnap();
break;
}
}
private OnScreenHint mStorageHint;
private void updateStorageHint(int remaining) {
String noStorageText = null;
if (remaining == MenuHelper.NO_STORAGE_ERROR) {
String state = Environment.getExternalStorageState();
if (state == Environment.MEDIA_CHECKING ||
ImageManager.isMediaScannerScanning(getContentResolver())) {
noStorageText = getString(R.string.preparing_sd);
} else {
noStorageText = getString(R.string.no_storage);
}
} else if (remaining < 1) {
noStorageText = getString(R.string.not_enough_space);
}
if (noStorageText != null) {
if (mStorageHint == null) {
mStorageHint = OnScreenHint.makeText(this, noStorageText);
} else {
mStorageHint.setText(noStorageText);
}
mStorageHint.show();
} else if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
}
private void installIntentFilter() {
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addDataScheme("file");
registerReceiver(mReceiver, intentFilter);
mDidRegister = true;
}
private void initializeFocusTone() {
// Initialize focus tone generator.
try {
mFocusToneGenerator = new ToneGenerator(
AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
} catch (Throwable ex) {
Log.w(TAG, "Exception caught while creating tone generator: ", ex);
mFocusToneGenerator = null;
}
}
private void readPreference() {
mRecordLocation = mPreferences.getBoolean(
"pref_camera_recordlocation_key", false);
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE,
getString(R.string.pref_camera_focusmode_default));
}
@Override
public void onResume() {
super.onResume();
mPausing = false;
mJpegPictureCallbackTime = 0;
mImageCapture = new ImageCapture();
// Start the preview if it is not started.
if (!mPreviewing && !mStartPreviewFail) {
try {
startPreview();
} catch (CameraHardwareException e) {
showCameraErrorAndFinish();
return;
}
}
if (mSurfaceHolder != null) {
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
}
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
private static ImageManager.DataLocation dataLocation() {
return ImageManager.DataLocation.EXTERNAL;
}
@Override
protected void onPause() {
mPausing = true;
stopPreview();
// Close the camera now because other activities may need to use it.
closeCamera();
if (mSettings != null && mSettings.isVisible()) {
mSettings.setVisible(false);
}
if (mFirstTimeInitialized) {
mOrientationListener.disable();
mGpsIndicator.setVisibility(View.INVISIBLE);
if (!mIsImageCaptureIntent) {
mThumbController.storeData(
ImageManager.getLastImageThumbPath());
}
hidePostCaptureAlert();
}
if (mDidRegister) {
unregisterReceiver(mReceiver);
mDidRegister = false;
}
stopReceivingLocationUpdates();
if (mFocusToneGenerator != null) {
mFocusToneGenerator.release();
mFocusToneGenerator = null;
}
if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mImageCapture.clearLastBitmap();
mImageCapture = null;
// This is necessary to make the ZoomButtonsController unregister
// its configuration change receiver.
if (mZoomButtons != null) {
mZoomButtons.setVisible(false);
}
// Remove the messages in the event queue.
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mHandler.removeMessages(RESTART_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
super.onPause();
}
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CROP_MSG: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
setResult(resultCode, intent);
finish();
File path = getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
}
private void autoFocus() {
// Initiate autofocus only when preview is started and snapshot is not
// in progress.
if (canTakePicture()) {
Log.v(TAG, "Start autofocus.");
if (mZoomButtons != null) mZoomButtons.setVisible(false);
mFocusStartTime = System.currentTimeMillis();
mFocusState = FOCUSING;
updateFocusIndicator();
mCameraDevice.autoFocus(mAutoFocusCallback);
}
}
private void cancelAutoFocus() {
// User releases half-pressed focus key.
if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
|| mFocusState == FOCUS_FAIL) {
Log.v(TAG, "Cancel autofocus.");
mCameraDevice.cancelAutoFocus();
}
if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
clearFocusState();
}
}
private void clearFocusState() {
mFocusState = FOCUS_NOT_STARTED;
updateFocusIndicator();
}
private void updateFocusIndicator() {
if (mFocusRectangle == null) return;
if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
mFocusRectangle.showStart();
} else if (mFocusState == FOCUS_SUCCESS) {
mFocusRectangle.showSuccess();
} else if (mFocusState == FOCUS_FAIL) {
mFocusRectangle.showFail();
} else {
mFocusRectangle.clear();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (!isCameraIdle()) {
// ignore backs while we're taking a picture
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
doFocus(true);
}
return true;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
doSnap();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, doFocus() will be
// called again but it is fine.
doFocus(true);
if (mShutterButton.isInTouchMode()) {
mShutterButton.requestFocusFromTouch();
} else {
mShutterButton.requestFocus();
}
mShutterButton.setPressed(true);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
doFocus(false);
}
return true;
}
return super.onKeyUp(keyCode, event);
}
private void doSnap() {
// If the user has half-pressed the shutter and focus is completed, we
// can take the photo right away. If the focus mode is infinity, we can
// also take the photo.
if (mFocusMode.equals(getString(
R.string.pref_camera_focusmode_value_infinity))
|| (mFocusState == FOCUS_SUCCESS
|| mFocusState == FOCUS_FAIL)) {
if (mZoomButtons != null) mZoomButtons.setVisible(false);
mImageCapture.onSnap();
} else if (mFocusState == FOCUSING) {
// Half pressing the shutter (i.e. the focus button event) will
// already have requested AF for us, so just request capture on
// focus here.
mFocusState = FOCUSING_SNAP_ON_FINISH;
} else if (mFocusState == FOCUS_NOT_STARTED) {
// Focus key down event is dropped for some reasons. Just ignore.
}
}
private void doFocus(boolean pressed) {
// Do the focus if the mode is auto. No focus needed in infinity mode.
if (mFocusMode.equals(getString(
R.string.pref_camera_focusmode_value_auto))) {
if (pressed) { // Focus key down.
autoFocus();
} else { // Focus key up.
cancelAutoFocus();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Make sure we have a surface in the holder before proceeding.
if (holder.getSurface() == null) {
Log.d(TAG, "holder.getSurface() == null");
return;
}
// The mCameraDevice will be null if it fails to connect to the camera
// hardware. In this case we will show a dialog and then finish the
// activity, so it's OK to ignore it.
if (mCameraDevice == null) return;
mSurfaceHolder = holder;
mViewFinderWidth = w;
mViewFinderHeight = h;
// Sometimes surfaceChanged is called after onPause. Ignore it.
if (mPausing || isFinishing()) return;
// Set preview display if the surface is being created. Preview was
// already started.
if (holder.isCreating()) {
setPreviewDisplay(holder);
}
// If first time initialization is not finished, send a message to do
// it later. We want to finish surfaceChanged as soon as possible to let
// user see preview first.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
stopPreview();
mSurfaceHolder = null;
}
private void closeCamera() {
if (mCameraDevice != null) {
CameraHolder.instance().release();
mCameraDevice = null;
mPreviewing = false;
}
}
private void ensureCameraDevice() throws CameraHardwareException {
if (mCameraDevice == null) {
mCameraDevice = CameraHolder.instance().open();
}
}
private void updateLastImage() {
IImageList list = ImageManager.makeImageList(
mContentResolver,
dataLocation(),
ImageManager.INCLUDE_IMAGES,
ImageManager.SORT_ASCENDING,
ImageManager.CAMERA_IMAGE_BUCKET_ID);
int count = list.getCount();
if (count > 0) {
IImage image = list.getImageAt(count - 1);
Uri uri = image.fullSizeImageUri();
mThumbController.setData(uri, image.miniThumbBitmap());
} else {
mThumbController.setData(null, null);
}
list.close();
}
private void showCameraErrorAndFinish() {
Resources ress = getResources();
Util.showFatalErrorAndFinish(Camera.this,
ress.getString(R.string.camera_error_title),
ress.getString(R.string.cannot_connect_camera));
}
private void restartPreview() {
// make sure the surfaceview fills the whole screen when previewing
mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
try {
startPreview();
} catch (CameraHardwareException e) {
showCameraErrorAndFinish();
return;
}
// Calculate this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
calculatePicturesRemaining();
}
private void setPreviewDisplay(SurfaceHolder holder) {
try {
mCameraDevice.setPreviewDisplay(holder);
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("setPreviewDisplay failed", ex);
}
}
private void startPreview() throws CameraHardwareException {
if (mPausing || isFinishing()) return;
ensureCameraDevice();
// If we're previewing already, stop the preview first (this will blank
// the screen).
if (mPreviewing) stopPreview();
setPreviewDisplay(mSurfaceHolder);
setCameraParameter();
final long wallTimeStart = SystemClock.elapsedRealtime();
final long threadTimeStart = Debug.threadCpuTimeNanos();
// Set one shot preview callback for latency measurement.
mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
mCameraDevice.setErrorCallback(mErrorCallback);
try {
Log.v(TAG, "startPreview");
mCameraDevice.startPreview();
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("startPreview failed", ex);
}
mPreviewing = true;
mStatus = IDLE;
long threadTimeEnd = Debug.threadCpuTimeNanos();
long wallTimeEnd = SystemClock.elapsedRealtime();
if ((wallTimeEnd - wallTimeStart) > 3000) {
Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
+ " ms. Thread time was"
+ (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
}
}
private void stopPreview() {
if (mCameraDevice != null && mPreviewing) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
}
mPreviewing = false;
// If auto focus was in progress, it would have been canceled.
clearFocusState();
}
private void resizeForPreviewAspectRatio(View v) {
ViewGroup.LayoutParams params;
params = v.getLayoutParams();
Size size = mParameters.getPreviewSize();
params.width = (int) (params.height * size.width / size.height);
Log.v(TAG, "resize to " + params.width + "x" + params.height);
v.setLayoutParams(params);
}
private Size getOptimalPreviewSize(List<Size> sizes) {
Size optimalSize = null;
if (sizes != null) {
optimalSize = sizes.get(0);
for (int i = 1; i < sizes.size(); i++) {
if (Math.abs(sizes.get(i).height - mViewFinderHeight) <
Math.abs(optimalSize.height - mViewFinderHeight)) {
optimalSize = sizes.get(i);
}
}
Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x"
+ optimalSize.height);
}
return optimalSize;
}
private void setCameraParameter() {
mParameters = mCameraDevice.getParameters();
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
// Set a preview size that is closest to the viewfinder height.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes);
if (optimalSize != null) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE,
getString(R.string.pref_camera_picturesize_default));
setCameraPictureSizeIfSupported(pictureSize);
// Set JPEG quality.
String jpegQuality = mPreferences.getString(
CameraSettings.KEY_JPEG_QUALITY,
getString(R.string.pref_camera_jpegquality_default));
mParameters.setJpegQuality(Integer.parseInt(jpegQuality));
// Set flash mode.
if (mParameters.getSupportedFlashModes() != null) {
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE, "auto");
mParameters.setFlashMode(flashMode);
}
// Set white balance parameter.
if (mParameters.getSupportedWhiteBalance() != null) {
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
getString(R.string.pref_camera_whitebalance_default));
mParameters.setWhiteBalance(whiteBalance);
}
// Set color effect parameter.
if (mParameters.getSupportedColorEffects() != null) {
String colorEffect = mPreferences.getString(
CameraSettings.KEY_COLOR_EFFECT,
getString(R.string.pref_camera_coloreffect_default));
mParameters.setColorEffect(colorEffect);
}
mCameraDevice.setParameters(mParameters);
}
private void gotoGallery() {
MenuHelper.gotoCameraImageGallery(this);
}
private void viewLastImage() {
if (mThumbController.isUriValid()) {
Uri targetUri = mThumbController.getUri();
targetUri = targetUri.buildUpon().appendQueryParameter(
"bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
Intent intent = new Intent(this, ReviewImage.class);
intent.setData(targetUri);
intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
intent.putExtra("com.android.camera.ReviewMode", true);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "review image fail", ex);
}
} else {
Log.e(TAG, "Can't view last image.");
}
}
private void startReceivingLocationUpdates() {
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0F,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0F,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
}
}
private void stopReceivingLocationUpdates() {
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private Location getCurrentLocation() {
// go in best to worst order
for (int i = 0; i < mLocationListeners.length; i++) {
Location l = mLocationListeners[i].current();
if (l != null) return l;
}
return null;
}
private boolean isCameraIdle() {
return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
}
private boolean isImageCaptureIntent() {
String action = getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
}
private void showPostCaptureAlert() {
if (mIsImageCaptureIntent) {
findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
int[] pickIds = {R.id.btn_retake, R.id.btn_done};
for (int id : pickIds) {
View button = findViewById(id);
((View) button.getParent()).setVisibility(View.VISIBLE);
}
}
}
private void hidePostCaptureAlert() {
if (mIsImageCaptureIntent) {
findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
int[] pickIds = {R.id.btn_retake, R.id.btn_done};
for (int id : pickIds) {
View button = findViewById(id);
((View) button.getParent()).setVisibility(View.GONE);
}
}
}
private int calculatePicturesRemaining() {
mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
return mPicturesRemaining;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// Only show the menu when camera is idle.
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(isCameraIdle());
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
if (mIsImageCaptureIntent) {
// No options menu for attach mode.
return false;
} else {
addBaseMenuItems(menu);
}
return true;
}
private void addBaseMenuItems(Menu menu) {
MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
MenuHelper.POSITION_GOTO_GALLERY,
R.string.camera_gallery_photos_text)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
gotoGallery();
return true;
}
});
gallery.setIcon(android.R.drawable.ic_menu_gallery);
mGalleryItems.add(gallery);
MenuItem item = menu.add(Menu.NONE, Menu.NONE,
MenuHelper.POSITION_CAMERA_SETTING, R.string.settings)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (mSettings == null) {
mSettings = new OnScreenSettings(
findViewById(R.id.camera_preview));
CameraSettings helper =
new CameraSettings(Camera.this, mParameters);
mSettings.setPreferenceScreen(helper
.getPreferenceScreen(R.xml.camera_preferences));
}
mSettings.setVisible(true);
return true;
}
});
item.setIcon(android.R.drawable.ic_menu_preferences);
}
public boolean onSwitchChanged(Switcher source, boolean onOff) {
if (onOff == SWITCH_VIDEO) {
if (!isCameraIdle()) return false;
MenuHelper.gotoVideoMode(this);
finish();
}
return true;
}
public void onFlashModeChanged(String modeString) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_FLASH_MODE, modeString);
editor.commit();
if (!mPausing) {
mParameters.setFlashMode(modeString);
mCameraDevice.setParameters(mParameters);
}
}
private void setCameraPictureSizeIfSupported(String sizeString) {
List<Size> pictureSizes = mParameters.getSupportedPictureSizes();
if (pictureSizes != null) {
int index = sizeString.indexOf('x');
int width = Integer.parseInt(sizeString.substring(0, index));
int height = Integer.parseInt(sizeString.substring(index + 1));
for (Size size: pictureSizes) {
if (size.width == width && size.height == height) {
mParameters.setPictureSize(width, height);
break;
}
}
}
}
public void onSharedPreferenceChanged(
SharedPreferences preferences, String key) {
// ignore the events after "onPause()"
if (mPausing) return;
if (CameraSettings.KEY_FLASH_MODE.equals(key)) {
mParameters.setFlashMode(preferences.getString(key, "auto"));
mCameraDevice.setParameters(mParameters);
} else if (CameraSettings.KEY_FOCUS_MODE.equals(key)) {
mFocusMode = preferences.getString(key,
getString(R.string.pref_camera_focusmode_default));
} else if (CameraSettings.KEY_PICTURE_SIZE.equals(key)) {
String pictureSize = preferences.getString(key,
getString(R.string.pref_camera_picturesize_default));
setCameraPictureSizeIfSupported(pictureSize);
mCameraDevice.setParameters(mParameters);
} else if (CameraSettings.KEY_JPEG_QUALITY.equals(key)) {
String jpegQuality = preferences.getString(key,
getString(R.string.pref_camera_jpegquality_default));
mParameters.setJpegQuality(Integer.parseInt(jpegQuality));
mCameraDevice.setParameters(mParameters);
} else if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) {
mRecordLocation = preferences.getBoolean(key, false);
if (mRecordLocation) {
startReceivingLocationUpdates();
} else {
stopReceivingLocationUpdates();
}
} else if (CameraSettings.KEY_COLOR_EFFECT.equals(key)) {
String colorEffect = preferences.getString(key,
getString(R.string.pref_camera_coloreffect_default));
mParameters.setColorEffect(colorEffect);
mCameraDevice.setParameters(mParameters);
} else if (CameraSettings.KEY_WHITE_BALANCE.equals(key)) {
String whiteBalance = preferences.getString(key,
getString(R.string.pref_camera_whitebalance_default));
mParameters.setWhiteBalance(whiteBalance);
mCameraDevice.setParameters(mParameters);
} else if (CameraSettings.KEY_SCENE_MODE.equals(key)) {
String sceneMode = preferences.getString(key,
getString(R.string.pref_camera_scenemode_default));
mParameters.setSceneMode(sceneMode);
mCameraDevice.setParameters(mParameters);
}
}
}
class FocusRectangle extends View {
@SuppressWarnings("unused")
private static final String TAG = "FocusRectangle";
public FocusRectangle(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void setDrawable(int resid) {
setBackgroundDrawable(getResources().getDrawable(resid));
}
public void showStart() {
setDrawable(R.drawable.focus_focusing);
}
public void showSuccess() {
setDrawable(R.drawable.focus_focused);
}
public void showFail() {
setDrawable(R.drawable.focus_focus_failed);
}
public void clear() {
setBackgroundDrawable(null);
}
}
// FlashButton changes state every time it is clicked.
// The ModeChangeListener notifies that event.
class FlashButton extends ImageView implements View.OnClickListener {
private static final String TAG = "FlashButton";
private static final int MODE_OFF = 0;
private static final int MODE_ON = 1;
private static final int MODE_AUTO = 2;
private static final String[] MODE_STRINGS = new String[] {
"off", "on", "auto"
};
private static final int[] FLASH_IMAGES = new int[] {
R.drawable.flash_off,
R.drawable.flash_on,
R.drawable.flash_auto
};
private int mCurrentMode;
private ModeChangeListener mListener;
public interface ModeChangeListener {
public void onFlashModeChanged(String modeString);
}
public FlashButton(Context context, AttributeSet attrs) {
super(context, attrs);
updateMode(MODE_AUTO);
setOnClickListener(this);
}
public void setMode(String modeString) {
for (int i = 0; i < MODE_STRINGS.length; i++) {
if (MODE_STRINGS[i].equals(modeString)) {
updateModeIfNecessary(i);
return;
}
}
Log.w(TAG, "Unknown mode: " + modeString);
}
public void setListener(ModeChangeListener listener) {
mListener = listener;
}
public void onClick(View v) {
int nextMode = (mCurrentMode + 1) % FLASH_IMAGES.length;
updateMode(nextMode);
}
private void updateModeIfNecessary(int mode) {
if (mode == mCurrentMode) return;
if (mode < 0 || mode >= FLASH_IMAGES.length) {
return;
}
updateMode(mode);
}
private void updateMode(int mode) {
mCurrentMode = mode;
setImageResource(FLASH_IMAGES[mode]);
if (mListener != null) {
mListener.onFlashModeChanged(MODE_STRINGS[mode]);
}
}
}
|