├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ └── bg_shadow.9.png
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── hzitoun
│ │ │ │ └── camera2SecretPictureTaker
│ │ │ │ ├── listeners
│ │ │ │ └── PictureCapturingListener.java
│ │ │ │ ├── services
│ │ │ │ ├── APictureCapturingService.java
│ │ │ │ └── PictureCapturingServiceImpl.java
│ │ │ │ └── activities
│ │ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── hzitoun
│ │ │ └── camera2SecretPictureTaker
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── hzitoun
│ │ └── camera2SecretPictureTaker
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── preview
└── demo.png
├── .idea
├── copyright
│ └── profiles_settings.xml
├── modules.xml
├── runConfigurations.xml
├── gradle.xml
├── compiler.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── .travis.yml
├── gradle.properties
├── LICENSE
├── gradlew.bat
├── gradlew
└── README.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/preview/demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/preview/demo.png
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_shadow.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/drawable/bg_shadow.9.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hzitoun/android-camera2-secret-picture-taker/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Camera 2 Secret Picture Taker
3 | Take photos
4 | Front Camera Picture
5 | Back Camera Picture
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/test/java/com/hzitoun/camera2SecretPictureTaker/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | # User-specific configurations
11 | .idea/libraries/
12 | .idea/workspace.xml
13 | .idea/tasks.xml
14 | .idea/.name
15 | .idea/compiler.xml
16 | .idea/copyright/profiles_settings.xml
17 | .idea/encodings.xml
18 | .idea/misc.xml
19 | .idea/modules.xml
20 | .idea/scopes/scope_settings.xml
21 | .idea/dictionaries
22 | .idea/vcs.xml
23 | .idea/jsLibraryMappings.xml
24 | .idea/datasources.xml
25 | .idea/dataSources.ids
26 | .idea/sqlDataSources.xml
27 | .idea/dynamic.xml
28 | .idea/uiDesigner.xml
29 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | jdk: oraclejdk8
3 | env:
4 | android:
5 | components:
6 | - tools
7 | - build-tools-25.0.2
8 | - android-25
9 | - platform-tools
10 | - extra-android-m2repository
11 | before_install:
12 | - chmod +x gradlew
13 | install:
14 | - echo y | android update sdk -u -a -t tools
15 | - echo y | android update sdk -u -a -t platform-tools
16 | - echo y | android update sdk -u -a -t build-tools-25.0.2
17 | - echo y | android update sdk -u -a -t android-25
18 | - echo y | android update sdk -u -a -t extra-google-m2repository
19 | - echo y | android update sdk -u -a -t extra-android-m2repository
20 | script:
21 | - ./gradlew assembleRelease
22 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\hamed\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/hzitoun/camera2SecretPictureTaker/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.hzitoun.camera2secretpicturetaker", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hzitoun/camera2SecretPictureTaker/listeners/PictureCapturingListener.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker.listeners;
2 |
3 | import java.util.TreeMap;
4 |
5 | /**
6 | * Picture capturing listener
7 | *
8 | * @author hzitoun (zitoun.hamed@gmail.com)
9 | */
10 | public interface PictureCapturingListener {
11 |
12 | /**
13 | * a callback called when we've done taking a picture from a single camera
14 | * (use this method if you don't want to wait for ALL taken pictures to be ready @see onDoneCapturingAllPhotos)
15 | *
16 | * @param pictureUrl taken picture's location on the device
17 | * @param pictureData taken picture's data as a byte array
18 | */
19 | void onCaptureDone(String pictureUrl, byte[] pictureData);
20 |
21 | /**
22 | * a callback called when we've done taking pictures from ALL AVAILABLE cameras
23 | * OR when NO camera was detected on the device
24 | *
25 | * @param picturesTaken : a Map
26 | */
27 | void onDoneCapturingAllPhotos(TreeMap picturesTaken);
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
16 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Hamed ZITOUN
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.hzitoun.camera2secretpicturetaker"
8 | minSdkVersion 21
9 | targetSdkVersion 25
10 | versionCode 2
11 | versionName "1.0.1"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | jackOptions {
14 | enabled true
15 | }
16 | }
17 | compileOptions {
18 | sourceCompatibility JavaVersion.VERSION_1_8
19 | targetCompatibility JavaVersion.VERSION_1_8
20 | }
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | }
28 |
29 | dependencies {
30 | compile fileTree(dir: 'libs', include: ['*.jar'])
31 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
32 | exclude group: 'com.android.support', module: 'support-annotations'
33 | })
34 | compile 'com.android.support:appcompat-v7:25.1.0'
35 | testCompile 'junit:junit:4.12'
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hzitoun/camera2SecretPictureTaker/services/APictureCapturingService.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker.services;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.hardware.camera2.CameraManager;
6 | import android.util.SparseIntArray;
7 | import android.view.Surface;
8 |
9 | import com.hzitoun.camera2SecretPictureTaker.listeners.PictureCapturingListener;
10 |
11 | /**
12 | * Abstract Picture Taking Service.
13 | *
14 | * @author hzitoun (zitoun.hamed@gmail.com)
15 | */
16 | public abstract class APictureCapturingService {
17 |
18 | private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
19 |
20 | static {
21 | ORIENTATIONS.append(Surface.ROTATION_0, 90);
22 | ORIENTATIONS.append(Surface.ROTATION_90, 0);
23 | ORIENTATIONS.append(Surface.ROTATION_180, 270);
24 | ORIENTATIONS.append(Surface.ROTATION_270, 180);
25 | }
26 |
27 | private final Activity activity;
28 | final Context context;
29 | final CameraManager manager;
30 |
31 | /***
32 | * constructor.
33 | *
34 | * @param activity the activity used to get display manager and the application context
35 | */
36 | APictureCapturingService(final Activity activity) {
37 | this.activity = activity;
38 | this.context = activity.getApplicationContext();
39 | this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
40 | }
41 |
42 | /***
43 | * @return orientation
44 | */
45 | int getOrientation() {
46 | final int rotation = this.activity.getWindowManager().getDefaultDisplay().getRotation();
47 | return ORIENTATIONS.get(rotation);
48 | }
49 |
50 |
51 | /**
52 | * starts pictures capturing process.
53 | *
54 | * @param listener picture capturing listener
55 | */
56 | public abstract void startCapturing(final PictureCapturingListener listener);
57 | }
58 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
18 |
19 |
24 |
25 |
31 |
32 |
33 |
34 |
39 |
40 |
45 |
46 |
47 |
48 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hzitoun/camera2SecretPictureTaker/activities/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker.activities;
2 |
3 | import android.Manifest;
4 | import android.annotation.TargetApi;
5 | import android.content.pm.PackageManager;
6 | import android.graphics.Bitmap;
7 | import android.graphics.BitmapFactory;
8 | import android.os.Build;
9 | import android.os.Bundle;
10 | import android.support.annotation.NonNull;
11 | import android.support.v4.app.ActivityCompat;
12 | import android.support.v4.content.ContextCompat;
13 | import android.support.v7.app.AppCompatActivity;
14 | import android.widget.Button;
15 | import android.widget.ImageView;
16 | import android.widget.Toast;
17 |
18 | import com.hzitoun.camera2SecretPictureTaker.R;
19 | import com.hzitoun.camera2SecretPictureTaker.listeners.PictureCapturingListener;
20 | import com.hzitoun.camera2SecretPictureTaker.services.APictureCapturingService;
21 | import com.hzitoun.camera2SecretPictureTaker.services.PictureCapturingServiceImpl;
22 |
23 | import java.util.ArrayList;
24 | import java.util.List;
25 | import java.util.TreeMap;
26 |
27 |
28 | /**
29 | * App's Main Activity showing a simple usage of the picture taking service.
30 | * @author hzitoun (zitoun.hamed@gmail.com)
31 | */
32 | public class MainActivity extends AppCompatActivity implements PictureCapturingListener, ActivityCompat.OnRequestPermissionsResultCallback {
33 |
34 | private static final String[] requiredPermissions = {
35 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
36 | Manifest.permission.CAMERA,
37 | };
38 | private static final int MY_PERMISSIONS_REQUEST_ACCESS_CODE = 1;
39 |
40 | private ImageView uploadBackPhoto;
41 | private ImageView uploadFrontPhoto;
42 |
43 | //The capture service
44 | private APictureCapturingService pictureService;
45 |
46 | @Override
47 | protected void onCreate(Bundle savedInstanceState) {
48 | super.onCreate(savedInstanceState);
49 | setContentView(R.layout.activity_main);
50 | checkPermissions();
51 | uploadBackPhoto = (ImageView) findViewById(R.id.backIV);
52 | uploadFrontPhoto = (ImageView) findViewById(R.id.frontIV);
53 | final Button btn = (Button) findViewById(R.id.startCaptureBtn);
54 | // getting instance of the Service from PictureCapturingServiceImpl
55 | pictureService = PictureCapturingServiceImpl.getInstance(this);
56 | btn.setOnClickListener(v -> {
57 | showToast("Starting capture!");
58 | pictureService.startCapturing(this);
59 | });
60 | }
61 |
62 | private void showToast(final String text) {
63 | runOnUiThread(() ->
64 | Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show()
65 | );
66 | }
67 |
68 | /**
69 | * We've finished taking pictures from all phone's cameras
70 | */
71 | @Override
72 | public void onDoneCapturingAllPhotos(TreeMap picturesTaken) {
73 | if (picturesTaken != null && !picturesTaken.isEmpty()) {
74 | showToast("Done capturing all photos!");
75 | return;
76 | }
77 | showToast("No camera detected!");
78 | }
79 |
80 | /**
81 | * Displaying the pictures taken.
82 | */
83 | @Override
84 | public void onCaptureDone(String pictureUrl, byte[] pictureData) {
85 | if (pictureData != null && pictureUrl != null) {
86 | runOnUiThread(() -> {
87 | final Bitmap bitmap = BitmapFactory.decodeByteArray(pictureData, 0, pictureData.length);
88 | final int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
89 | final Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
90 | if (pictureUrl.contains("0_pic.jpg")) {
91 | uploadBackPhoto.setImageBitmap(scaled);
92 | } else if (pictureUrl.contains("1_pic.jpg")) {
93 | uploadFrontPhoto.setImageBitmap(scaled);
94 | }
95 | });
96 | showToast("Picture saved to " + pictureUrl);
97 | }
98 | }
99 |
100 | @Override
101 | public void onRequestPermissionsResult(int requestCode,
102 | @NonNull String permissions[], @NonNull int[] grantResults) {
103 | switch (requestCode) {
104 | case MY_PERMISSIONS_REQUEST_ACCESS_CODE: {
105 | if (!(grantResults.length > 0
106 | && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
107 | checkPermissions();
108 | }
109 | }
110 | }
111 | }
112 |
113 | /**
114 | * checking permissions at Runtime.
115 | */
116 | @TargetApi(Build.VERSION_CODES.M)
117 | private void checkPermissions() {
118 | final List neededPermissions = new ArrayList<>();
119 | for (final String permission : requiredPermissions) {
120 | if (ContextCompat.checkSelfPermission(getApplicationContext(),
121 | permission) != PackageManager.PERMISSION_GRANTED) {
122 | neededPermissions.add(permission);
123 | }
124 | }
125 | if (!neededPermissions.isEmpty()) {
126 | requestPermissions(neededPermissions.toArray(new String[]{}),
127 | MY_PERMISSIONS_REQUEST_ACCESS_CODE);
128 | }
129 | }
130 | }
131 |
132 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](https://travis-ci.org/hzitoun/android-camera2-secret-picture-taker)
4 |
5 | # 📸 Android Camera2 Secret Picture Taker (AC2SPT)
6 |
7 | Take pictures secretly (without preview or launching device's camera app) from all available cameras using Android CAMERA2 API.
8 | The Camera2 API replaces the deprecated Camera class.
9 | ___
10 |
11 | ## How can I support this project?
12 | - If you have enjoyed the project and it helped you creating a project, building an app, starting a business. You could encourage and support me on patreon https://www.patreon.com/hzitoun 🤗 !
13 | - Star this GitHub repo :star:
14 | - Create pull requests, submit bugs, suggest new features or documentation updates :wrench:
15 |
16 | ## Usage
17 |
18 | 1. Implement the interface ```PictureCapturingListener``` (your capture listener) and override the following methods:
19 | - **void onDoneCapturingAllPhotos(TreeMap picturesTaken)** which is called when we've done taking pictures from ALL available cameras OR when NO camera was detected on the device;
20 | - **void onCaptureDone(String pictureUrl, byte[] pictureData)** to get a couple (picture Url, picture Data). Use this method if you don't want to wait for ALL pictures to be ready;
21 | 2. Create a new instance of ```APictureCapturingService``` using ```PictureCapturingServiceImpl#getInstance()``` method;
22 | 3. **Start capture** by calling the method ```APictureCapturingService#startCapturing(PictureCapturingListener listener) ``` and pass the listener you've just implemented (**step 1**)
23 |
24 | ## Sample
25 |
26 | Here, I've chosen to just display the two pictures taken within a vertical linear layout. Here is a code snippet of how to use the service:
27 |
28 | ```java
29 | public class MainActivity extends AppCompatActivity implements PictureCapturingListener, ActivityCompat.OnRequestPermissionsResultCallback {
30 | private APictureCapturingService pictureService;
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_main);
36 | //check for camera and external storage permissions
37 | checkPermissions();
38 | final Button btn = (Button) findViewById(R.id.startCaptureBtn);
39 | pictureService = PictureCapturingServiceImpl.getInstance(this);
40 | //start capturing when clicking on the button
41 | btn.setOnClickListener(v ->
42 | pictureService.startCapturing(this)
43 | );
44 | }
45 |
46 | @Override
47 | public void onDoneCapturingAllPhotos(TreeMap picturesTaken) {
48 | if (picturesTaken != null && !picturesTaken.isEmpty()) {
49 | picturesTaken.forEach((pictureUrl, pictureData) -> {
50 | //convert the byte array 'pictureData' to a bitmap (no need to read the file from the external storage) but in case you
51 | //You can also use 'pictureUrl' which stores the picture's location on the device
52 | final Bitmap bitmap = BitmapFactory.decodeByteArray(pictureData, 0, pictureData.length);
53 | });
54 | showToast("Done capturing all photos!");
55 | return;
56 | }
57 | showToast("No camera detected!");
58 | }
59 |
60 | @Override
61 | public void onCaptureDone(String pictureUrl, byte[] pictureData) {
62 | if (pictureData != null && pictureUrl != null) {
63 | runOnUiThread(() -> {
64 | //convert byte array 'pictureData' to a bitmap (no need to read the file from the external storage)
65 | final Bitmap bitmap = BitmapFactory.decodeByteArray(pictureData, 0, pictureData.length);
66 | //scale image to avoid POTENTIAL "Bitmap too large to be uploaded into a texture" when displaying into an ImageView
67 | final int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
68 | final Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
69 | //do whatever you want with the bitmap or the scaled one...
70 | });
71 | showToast("Picture saved to " + pictureUrl);
72 | }
73 | }
74 |
75 | private void showToast(final String text) {
76 | runOnUiThread(() ->
77 | Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show()
78 | );
79 | }
80 |
81 | }
82 | ```
83 |
84 | Thanks to [maaudrana](https://github.com/maaudrana) for the logo :)
85 |
86 | ## Contributors
87 |
88 | Hamed ZITOUN
89 |
90 | ## Help
91 |
92 | If you run into issues, please don't hesitate to find help on the GitHub project.
93 |
94 | ## License
95 |
96 | The android-camera2-secret-picture-taker is covered by the MIT License.
97 |
98 | The MIT License (MIT)
99 |
100 | Copyright (c) 2022 Hamed ZITOUN and contributors to the android-camera2-secret-picture-taker project.
101 |
102 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
103 |
104 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
105 |
106 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
107 |
108 |
--------------------------------------------------------------------------------
/app/src/main/java/com/hzitoun/camera2SecretPictureTaker/services/PictureCapturingServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.hzitoun.camera2SecretPictureTaker.services;
2 |
3 | import android.Manifest;
4 | import android.annotation.TargetApi;
5 | import android.app.Activity;
6 | import android.content.pm.PackageManager;
7 | import android.graphics.ImageFormat;
8 | import android.hardware.camera2.CameraAccessException;
9 | import android.hardware.camera2.CameraCaptureSession;
10 | import android.hardware.camera2.CameraCharacteristics;
11 | import android.hardware.camera2.CameraDevice;
12 | import android.hardware.camera2.CameraMetadata;
13 | import android.hardware.camera2.CaptureRequest;
14 | import android.hardware.camera2.TotalCaptureResult;
15 | import android.hardware.camera2.params.StreamConfigurationMap;
16 | import android.media.Image;
17 | import android.media.ImageReader;
18 | import android.os.Build;
19 | import android.os.Environment;
20 | import android.os.Handler;
21 | import android.support.annotation.NonNull;
22 | import android.support.v4.app.ActivityCompat;
23 | import android.util.Log;
24 | import android.util.Size;
25 | import android.view.Surface;
26 |
27 | import com.hzitoun.camera2SecretPictureTaker.listeners.PictureCapturingListener;
28 |
29 | import java.io.File;
30 | import java.io.FileOutputStream;
31 | import java.io.IOException;
32 | import java.io.OutputStream;
33 | import java.nio.ByteBuffer;
34 | import java.util.ArrayList;
35 | import java.util.Arrays;
36 | import java.util.LinkedList;
37 | import java.util.List;
38 | import java.util.Queue;
39 | import java.util.TreeMap;
40 | import java.util.UUID;
41 |
42 |
43 | /**
44 | * The aim of this service is to secretly take pictures (without preview or opening device's camera app)
45 | * from all available cameras using Android Camera 2 API
46 | *
47 | * @author hzitoun (zitoun.hamed@gmail.com)
48 | */
49 |
50 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) //NOTE: camera 2 api was added in API level 21
51 | public class PictureCapturingServiceImpl extends APictureCapturingService {
52 |
53 | private static final String TAG = PictureCapturingServiceImpl.class.getSimpleName();
54 |
55 | private CameraDevice cameraDevice;
56 | private ImageReader imageReader;
57 | /***
58 | * camera ids queue.
59 | */
60 | private Queue cameraIds;
61 |
62 | private String currentCameraId;
63 | private boolean cameraClosed;
64 | /**
65 | * stores a sorted map of (pictureUrlOnDisk, PictureData).
66 | */
67 | private TreeMap picturesTaken;
68 | private PictureCapturingListener capturingListener;
69 |
70 | /***
71 | * private constructor, meant to force the use of {@link #getInstance} method
72 | */
73 | private PictureCapturingServiceImpl(final Activity activity) {
74 | super(activity);
75 | }
76 |
77 | /**
78 | * @param activity the activity used to get the app's context and the display manager
79 | * @return a new instance
80 | */
81 | public static APictureCapturingService getInstance(final Activity activity) {
82 | return new PictureCapturingServiceImpl(activity);
83 | }
84 |
85 | /**
86 | * Starts pictures capturing treatment.
87 | *
88 | * @param listener picture capturing listener
89 | */
90 | @Override
91 | public void startCapturing(final PictureCapturingListener listener) {
92 | this.picturesTaken = new TreeMap<>();
93 | this.capturingListener = listener;
94 | this.cameraIds = new LinkedList<>();
95 | try {
96 | final String[] cameraIds = manager.getCameraIdList();
97 | if (cameraIds.length > 0) {
98 | this.cameraIds.addAll(Arrays.asList(cameraIds));
99 | this.currentCameraId = this.cameraIds.poll();
100 | openCamera();
101 | } else {
102 | //No camera detected!
103 | capturingListener.onDoneCapturingAllPhotos(picturesTaken);
104 | }
105 | } catch (final CameraAccessException e) {
106 | Log.e(TAG, "Exception occurred while accessing the list of cameras", e);
107 | }
108 | }
109 |
110 | private void openCamera() {
111 | Log.d(TAG, "opening camera " + currentCameraId);
112 | try {
113 | if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
114 | == PackageManager.PERMISSION_GRANTED
115 | && ActivityCompat.checkSelfPermission(context,
116 | Manifest.permission.WRITE_EXTERNAL_STORAGE)
117 | == PackageManager.PERMISSION_GRANTED) {
118 | manager.openCamera(currentCameraId, stateCallback, null);
119 | }
120 | } catch (final CameraAccessException e) {
121 | Log.e(TAG, " exception occurred while opening camera " + currentCameraId, e);
122 | }
123 | }
124 |
125 | private final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
126 | @Override
127 | public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request,
128 | @NonNull TotalCaptureResult result) {
129 | super.onCaptureCompleted(session, request, result);
130 | if (picturesTaken.lastEntry() != null) {
131 | capturingListener.onCaptureDone(picturesTaken.lastEntry().getKey(), picturesTaken.lastEntry().getValue());
132 | Log.i(TAG, "done taking picture from camera " + cameraDevice.getId());
133 | }
134 | closeCamera();
135 | }
136 | };
137 |
138 |
139 | private final ImageReader.OnImageAvailableListener onImageAvailableListener = (ImageReader imReader) -> {
140 | final Image image = imReader.acquireLatestImage();
141 | final ByteBuffer buffer = image.getPlanes()[0].getBuffer();
142 | final byte[] bytes = new byte[buffer.capacity()];
143 | buffer.get(bytes);
144 | saveImageToDisk(bytes);
145 | image.close();
146 | };
147 |
148 | private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
149 | @Override
150 | public void onOpened(@NonNull CameraDevice camera) {
151 | cameraClosed = false;
152 | Log.d(TAG, "camera " + camera.getId() + " opened");
153 | cameraDevice = camera;
154 | Log.i(TAG, "Taking picture from camera " + camera.getId());
155 | //Take the picture after some delay. It may resolve getting a black dark photos.
156 | new Handler().postDelayed(() -> {
157 | try {
158 | takePicture();
159 | } catch (final CameraAccessException e) {
160 | Log.e(TAG, " exception occurred while taking picture from " + currentCameraId, e);
161 | }
162 | }, 500);
163 | }
164 |
165 | @Override
166 | public void onDisconnected(@NonNull CameraDevice camera) {
167 | Log.d(TAG, " camera " + camera.getId() + " disconnected");
168 | if (cameraDevice != null && !cameraClosed) {
169 | cameraClosed = true;
170 | cameraDevice.close();
171 | }
172 | }
173 |
174 | @Override
175 | public void onClosed(@NonNull CameraDevice camera) {
176 | cameraClosed = true;
177 | Log.d(TAG, "camera " + camera.getId() + " closed");
178 | //once the current camera has been closed, start taking another picture
179 | if (!cameraIds.isEmpty()) {
180 | takeAnotherPicture();
181 | } else {
182 | capturingListener.onDoneCapturingAllPhotos(picturesTaken);
183 | }
184 | }
185 |
186 |
187 | @Override
188 | public void onError(@NonNull CameraDevice camera, int error) {
189 | Log.e(TAG, "camera in error, int code " + error);
190 | if (cameraDevice != null && !cameraClosed) {
191 | cameraDevice.close();
192 | }
193 | }
194 | };
195 |
196 |
197 | private void takePicture() throws CameraAccessException {
198 | if (null == cameraDevice) {
199 | Log.e(TAG, "cameraDevice is null");
200 | return;
201 | }
202 | final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
203 | Size[] jpegSizes = null;
204 | StreamConfigurationMap streamConfigurationMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
205 | if (streamConfigurationMap != null) {
206 | jpegSizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
207 | }
208 | final boolean jpegSizesNotEmpty = jpegSizes != null && 0 < jpegSizes.length;
209 | int width = jpegSizesNotEmpty ? jpegSizes[0].getWidth() : 640;
210 | int height = jpegSizesNotEmpty ? jpegSizes[0].getHeight() : 480;
211 | final ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
212 | final List outputSurfaces = new ArrayList<>();
213 | outputSurfaces.add(reader.getSurface());
214 | final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
215 | captureBuilder.addTarget(reader.getSurface());
216 | captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
217 | captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation());
218 | reader.setOnImageAvailableListener(onImageAvailableListener, null);
219 | cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
220 | @Override
221 | public void onConfigured(@NonNull CameraCaptureSession session) {
222 | try {
223 | session.capture(captureBuilder.build(), captureListener, null);
224 | } catch (final CameraAccessException e) {
225 | Log.e(TAG, " exception occurred while accessing " + currentCameraId, e);
226 | }
227 | }
228 |
229 | @Override
230 | public void onConfigureFailed(@NonNull CameraCaptureSession session) {
231 | }
232 | }
233 | , null);
234 | }
235 |
236 |
237 | private void saveImageToDisk(final byte[] bytes) {
238 | final String cameraId = this.cameraDevice == null ? UUID.randomUUID().toString() : this.cameraDevice.getId();
239 | final File file = new File(Environment.getExternalStorageDirectory() + "/" + cameraId + "_pic.jpg");
240 | try (final OutputStream output = new FileOutputStream(file)) {
241 | output.write(bytes);
242 | this.picturesTaken.put(file.getPath(), bytes);
243 | } catch (final IOException e) {
244 | Log.e(TAG, "Exception occurred while saving picture to external storage ", e);
245 | }
246 | }
247 |
248 | private void takeAnotherPicture() {
249 | this.currentCameraId = this.cameraIds.poll();
250 | openCamera();
251 | }
252 |
253 | private void closeCamera() {
254 | Log.d(TAG, "closing camera " + cameraDevice.getId());
255 | if (null != cameraDevice && !cameraClosed) {
256 | cameraDevice.close();
257 | cameraDevice = null;
258 | }
259 | if (null != imageReader) {
260 | imageReader.close();
261 | imageReader = null;
262 | }
263 | }
264 |
265 |
266 | }
267 |
--------------------------------------------------------------------------------