├── .gitignore ├── .idea ├── .gitignore ├── .name ├── compiler.xml ├── deploymentTargetDropDown.xml ├── gradle.xml ├── kotlinc.xml ├── migrations.xml ├── misc.xml ├── other.xml └── vcs.xml ├── LICENSE.txt ├── README.md ├── build.gradle ├── docs ├── code-of-conduct.md └── contributing.md ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── scripts ├── copyright └── greclipse.properties ├── settings.gradle ├── step1 ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── google │ │ └── codelab │ │ └── camera2 │ │ ├── CameraActivity.kt │ │ └── CameraUtils.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ └── activity_camera.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-mdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ └── values │ ├── colors.xml │ ├── strings.xml │ └── themes.xml └── step2 ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main ├── AndroidManifest.xml ├── java └── com │ └── google │ └── codelab │ └── camera2 │ ├── CameraActivity.kt │ └── CameraUtils.kt └── res ├── drawable-v24 └── ic_launcher_foreground.xml ├── drawable └── ic_launcher_background.xml ├── layout └── activity_camera.xml ├── mipmap-anydpi-v26 ├── ic_launcher.xml └── ic_launcher_round.xml ├── mipmap-hdpi ├── ic_launcher.webp └── ic_launcher_round.webp ├── mipmap-mdpi ├── ic_launcher.webp └── ic_launcher_round.webp ├── mipmap-xhdpi ├── ic_launcher.webp └── ic_launcher_round.webp ├── mipmap-xxhdpi ├── ic_launcher.webp └── ic_launcher_round.webp ├── mipmap-xxxhdpi ├── ic_launcher.webp └── ic_launcher_round.webp └── values ├── colors.xml ├── strings.xml └── themes.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | Camera2 Codelab -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/deploymentTargetDropDown.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/migrations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 12 | 13 | 14 | 15 | 16 | 17 | 19 | -------------------------------------------------------------------------------- /.idea/other.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Support resizable surfaces in your camera app 2 | 3 | This folder contains the source code for the Camera2 codelab. 4 | 5 | ## License 6 | 7 | Copyright 2022 Google LLC 8 | 9 | Licensed under the Apache License, Version 2.0 (the "License"); 10 | you may not use this file except in compliance with the License. 11 | You may obtain a copy of the License at 12 | 13 | https://www.apache.org/licenses/LICENSE-2.0 14 | 15 | Unless required by applicable law or agreed to in writing, software 16 | distributed under the License is distributed on an "AS IS" BASIS, 17 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | See the License for the specific language governing permissions and 19 | limitations under the License. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | ext.kotlin_version = "1.7.10" 19 | ext.ktlint_version = '0.40.0' 20 | repositories { 21 | google() 22 | mavenCentral() 23 | } 24 | dependencies { 25 | classpath 'com.android.tools.build:gradle:7.1.3' 26 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 27 | } 28 | } 29 | 30 | plugins { 31 | id 'com.diffplug.spotless' version '5.7.0' 32 | } 33 | 34 | subprojects { 35 | apply plugin: 'com.diffplug.spotless' 36 | spotless { 37 | kotlin { 38 | target '**/*.kt' 39 | ktlint(ktlint_version).userData(['android': 'true']) 40 | licenseHeaderFile rootProject.file('scripts/copyright') 41 | } 42 | groovyGradle { 43 | target '**/*.gradle' // default target of groovyGradle 44 | // the Groovy Eclipse formatter extends the Java Eclipse formatter, 45 | // so it formats Java files by default (unless `excludeJava` is used). 46 | greclipse().configFile(rootProject.file('scripts/greclipse.properties')) 47 | licenseHeaderFile rootProject.file('scripts/copyright'), '(buildscript|apply)' 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /docs/code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, education, socio-economic status, nationality, personal appearance, 10 | race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or reject 41 | comments, commits, code, wiki edits, issues, and other contributions that are 42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any 43 | contributor for other behaviors that they deem inappropriate, threatening, 44 | offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when the Project 56 | Steward has a reasonable belief that an individual's behavior may have a 57 | negative impact on the project or its community. 58 | 59 | ## Conflict Resolution 60 | 61 | We do not believe that all conflict is bad; healthy debate and disagreement 62 | often yield positive results. However, it is never okay to be disrespectful or 63 | to engage in behavior that violates the project’s code of conduct. 64 | 65 | If you see someone violating the code of conduct, you are encouraged to address 66 | the behavior directly with those involved. Many issues can be resolved quickly 67 | and easily, and this gives people more control over the outcome of their 68 | dispute. If you are unable to resolve the matter for any reason, or if the 69 | behavior is threatening or harassing, report it. We are dedicated to providing 70 | an environment where participants feel welcome and safe. 71 | 72 | Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the 73 | Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to 74 | receive and address reported violations of the code of conduct. They will then 75 | work with a committee consisting of representatives from the Open Source 76 | Programs Office and the Google Open Source Strategy team. If for any reason you 77 | are uncomfortable reaching out to the Project Steward, please email 78 | opensource@google.com. 79 | 80 | We will investigate every complaint, but you may not receive a direct response. 81 | We will use our discretion in determining when and how to follow up on reported 82 | incidents, which may range from not taking action to permanent expulsion from 83 | the project and project-sponsored spaces. We will notify the accused of the 84 | report and provide them an opportunity to discuss it before any action is taken. 85 | The identity of the reporter will be omitted from the details of the report 86 | supplied to the accused. In potentially harmful situations, such as ongoing 87 | harassment or threats to anyone's safety, we may take action without notice. 88 | 89 | ## Attribution 90 | 91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 92 | available at 93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 94 | -------------------------------------------------------------------------------- /docs/contributing.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code Reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google/conduct/). 29 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Mar 12 19:17:39 CET 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /scripts/copyright: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright $YEAR Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | -------------------------------------------------------------------------------- /scripts/greclipse.properties: -------------------------------------------------------------------------------- 1 | #Whether to use 'space', 'tab' or 'mixed' (both) characters for indentation. 2 | #The default value is 'tab'. 3 | org.eclipse.jdt.core.formatter.tabulation.char=space 4 | 5 | #Number of spaces used for indentation in case 'space' characters 6 | #have been selected. The default value is 4. 7 | org.eclipse.jdt.core.formatter.tabulation.size=4 8 | 9 | #Number of spaces used for indentation in case 'mixed' characters 10 | #have been selected. The default value is 4. 11 | org.eclipse.jdt.core.formatter.indentation.size=4 12 | 13 | #Whether or not indentation characters are inserted into empty lines. 14 | #The default value is 'true'. 15 | org.eclipse.jdt.core.formatter.indent_empty_lines=false 16 | 17 | #Number of spaces used for multiline indentation. 18 | #The default value is 2. 19 | groovy.formatter.multiline.indentation=2 20 | 21 | #Length after which list are considered too long. These will be wrapped. 22 | #The default value is 30. 23 | groovy.formatter.longListLength=30 24 | 25 | #Whether opening braces position shall be the next line. 26 | #The default value is 'same'. 27 | groovy.formatter.braces.start=same 28 | 29 | #Whether closing braces position shall be the next line. 30 | #The default value is 'next'. 31 | groovy.formatter.braces.end=next 32 | 33 | #Remove unnecessary semicolons. The default value is 'false'. 34 | groovy.formatter.remove.unnecessary.semicolons=false 35 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | pluginManagement { 17 | repositories { 18 | gradlePluginPortal() 19 | google() 20 | mavenCentral() 21 | } 22 | } 23 | dependencyResolutionManagement { 24 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 25 | repositories { 26 | google() 27 | mavenCentral() 28 | } 29 | } 30 | rootProject.name = "Camera2 Codelab" 31 | include ':step1' 32 | include ':step2' 33 | -------------------------------------------------------------------------------- /step1/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /step1/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | apply plugin: 'kotlin-android' 19 | 20 | 21 | android { 22 | compileSdk 34 23 | 24 | defaultConfig { 25 | applicationId "com.example.camera2.preview.step1" 26 | minSdk 24 27 | targetSdk 34 28 | versionCode 1 29 | versionName "1.0" 30 | 31 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 32 | } 33 | 34 | buildTypes { 35 | release { 36 | minifyEnabled false 37 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 38 | } 39 | } 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | kotlinOptions { 45 | jvmTarget = '1.8' 46 | } 47 | buildFeatures { 48 | viewBinding true 49 | } 50 | } 51 | 52 | dependencies { 53 | implementation 'androidx.core:core-ktx:1.12.0' 54 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2' 55 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1' 56 | implementation 'androidx.appcompat:appcompat:1.6.1' 57 | implementation 'com.google.android.material:material:1.10.0' 58 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 59 | testImplementation 'junit:junit:4.13.2' 60 | androidTestImplementation 'androidx.test.ext:junit:1.1.5' 61 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' 62 | } -------------------------------------------------------------------------------- /step1/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /step1/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 21 | 22 | 29 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /step1/src/main/java/com/google/codelab/camera2/CameraActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.codelab.camera2 18 | 19 | import android.Manifest 20 | import android.annotation.SuppressLint 21 | import android.content.Context 22 | import android.content.pm.PackageManager 23 | import android.graphics.SurfaceTexture 24 | import android.hardware.camera2.CameraCaptureSession 25 | import android.hardware.camera2.CameraDevice 26 | import android.hardware.camera2.CameraManager 27 | import android.os.Bundle 28 | import android.os.Handler 29 | import android.os.HandlerThread 30 | import android.os.Looper 31 | import android.util.Log 32 | import android.view.Surface 33 | import android.view.TextureView 34 | import androidx.appcompat.app.AppCompatActivity 35 | import androidx.core.app.ActivityCompat 36 | import androidx.lifecycle.lifecycleScope 37 | import com.google.codelab.camera2.databinding.ActivityCameraBinding 38 | import kotlinx.coroutines.Dispatchers 39 | import kotlinx.coroutines.launch 40 | 41 | const val TAG = "CAMERA_ACTIVITY" 42 | const val CAMERA_PERMISSION_REQUEST_CODE = 1992 43 | 44 | open class CameraActivity : AppCompatActivity() { 45 | 46 | /** Main Looper*/ 47 | private val mainLooperHandler = Handler(Looper.getMainLooper()) 48 | 49 | /** [HandlerThread] where all camera operations run */ 50 | private val cameraThread = HandlerThread("MyCameraThread").apply { start() } 51 | 52 | /** [Handler] corresponding to [cameraThread] */ 53 | private val cameraHandler = Handler(cameraThread.looper) 54 | 55 | /** hardcoded back camera*/ 56 | private val cameraID = "0" 57 | 58 | /** Detects, characterizes, and connects to a CameraDevice (used for all camera operations) */ 59 | private val cameraManager: CameraManager by lazy { 60 | applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager 61 | } 62 | 63 | /** The [CameraDevice] that will be opened in this Activity */ 64 | private var cameraDevice: CameraDevice? = null 65 | 66 | /** [Surface] target of the CameraCaptureRequest*/ 67 | private var surface: Surface? = null 68 | 69 | /** Where the camera preview is displayed */ 70 | private lateinit var textureView: TextureView 71 | 72 | private lateinit var binding: ActivityCameraBinding 73 | 74 | /*** Codelab --> add the Display variables ***/ 75 | 76 | override fun onCreate(savedInstanceState: Bundle?) { 77 | super.onCreate(savedInstanceState) 78 | binding = ActivityCameraBinding.inflate(layoutInflater) 79 | setContentView(binding.root) 80 | textureView = binding.textureView 81 | 82 | /*** Codelab --> change rotation animation ***/ 83 | } 84 | 85 | override fun onStart() { 86 | super.onStart() 87 | openCameraWithPermissionCheck() 88 | } 89 | 90 | override fun onDestroy() { 91 | super.onDestroy() 92 | release() 93 | cameraThread.quitSafely() 94 | } 95 | 96 | private fun openCameraWithPermissionCheck() { 97 | if (ActivityCompat.checkSelfPermission( 98 | this, Manifest.permission.CAMERA 99 | ) == PackageManager.PERMISSION_GRANTED 100 | ) { 101 | openCamera() 102 | } else { 103 | ActivityCompat.requestPermissions( 104 | this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE 105 | ) 106 | } 107 | } 108 | 109 | @SuppressLint("MissingPermission") 110 | override fun onRequestPermissionsResult( 111 | requestCode: Int, 112 | permissions: Array, 113 | grantResults: IntArray 114 | ) { 115 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 116 | if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { 117 | if (grantResults.getOrNull(0) == PackageManager.PERMISSION_GRANTED) { 118 | openCamera() 119 | } else { 120 | finish() 121 | } 122 | } 123 | } 124 | 125 | @SuppressLint("MissingPermission") 126 | private fun openCamera() = lifecycleScope.launch(Dispatchers.Main) { 127 | cameraManager.openCamera(cameraID, cameraStateCallback, cameraHandler) 128 | } 129 | 130 | /** 131 | * Before creating the [CameraCaptureSession] we apply a transformation to the TextureView to 132 | * avoid distortion in the preview 133 | */ 134 | private fun createCaptureSession() { 135 | if (cameraDevice == null || !textureView.isAvailable) return 136 | 137 | /*** Codelab --> Change this function to accept display rotation ***/ 138 | val targetTexture = CameraUtils.buildTargetTexture( 139 | textureView, cameraManager.getCameraCharacteristics(cameraID) 140 | ) 141 | 142 | this.surface = Surface(targetTexture) 143 | try { 144 | cameraDevice?.createCaptureSession( 145 | listOf(surface), sessionStateCallback, cameraHandler 146 | ) 147 | } catch (t: Throwable) { 148 | Log.e(TAG, "Failed to create session.", t) 149 | } 150 | } 151 | 152 | private fun release() { 153 | try { 154 | surface?.release() 155 | cameraDevice?.close() 156 | } catch (t: Throwable) { 157 | Log.e(TAG, "Failed to release resources.", t) 158 | } 159 | } 160 | 161 | /*** Codelab --> Add DisplayListener ***/ 162 | 163 | private val cameraStateCallback = object : CameraDevice.StateCallback() { 164 | override fun onOpened(camera: CameraDevice) { 165 | cameraDevice = camera 166 | try { 167 | mainLooperHandler.post { 168 | if (textureView.isAvailable) { 169 | createCaptureSession() 170 | } 171 | textureView.surfaceTextureListener = surfaceTextureListener 172 | } 173 | } catch (t: Throwable) { 174 | release() 175 | Log.e(TAG, "Failed to initialize camera.", t) 176 | } 177 | } 178 | 179 | override fun onDisconnected(camera: CameraDevice) { 180 | cameraDevice = camera 181 | release() 182 | } 183 | 184 | override fun onError(camera: CameraDevice, error: Int) { 185 | cameraDevice = camera 186 | Log.e(TAG, "on Error: $error") 187 | } 188 | } 189 | 190 | private val sessionStateCallback = object : CameraCaptureSession.StateCallback() { 191 | override fun onConfigured(cameraCaptureSession: CameraCaptureSession) { 192 | try { 193 | val captureRequest = cameraDevice?.createCaptureRequest( 194 | CameraDevice.TEMPLATE_PREVIEW 195 | ) 196 | captureRequest?.addTarget(surface!!) 197 | cameraCaptureSession.setRepeatingRequest( 198 | captureRequest?.build()!!, null, cameraHandler 199 | ) 200 | } catch (t: Throwable) { 201 | Log.e(TAG, "Failed to open camera preview.", t) 202 | } 203 | } 204 | 205 | override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession) { 206 | Log.e(TAG, "Failed to configure camera.") 207 | } 208 | } 209 | 210 | /** 211 | * Create a capture session once the surface is available 212 | */ 213 | private val surfaceTextureListener = object : TextureView.SurfaceTextureListener { 214 | 215 | override fun onSurfaceTextureAvailable( 216 | surface: SurfaceTexture, 217 | width: Int, 218 | height: Int 219 | ) { 220 | createCaptureSession() 221 | } 222 | 223 | override fun onSurfaceTextureSizeChanged( 224 | surface: SurfaceTexture, 225 | width: Int, 226 | height: Int 227 | ) { 228 | /*** Codelab -> start a session here ***/ 229 | } 230 | override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} 231 | override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = false 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /step1/src/main/java/com/google/codelab/camera2/CameraUtils.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.codelab.camera2 18 | 19 | import android.graphics.SurfaceTexture 20 | import android.hardware.camera2.CameraCharacteristics 21 | import android.util.Size 22 | import android.view.TextureView 23 | 24 | object CameraUtils { 25 | 26 | /** Return the biggest preview size available which is smaller than the window */ 27 | private fun findBestPreviewSize(windowSize: Size, characteristics: CameraCharacteristics): 28 | Size { 29 | val supportedPreviewSizes: List = 30 | characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) 31 | ?.getOutputSizes(SurfaceTexture::class.java) 32 | ?.filter { SizeComparator.compare(it, windowSize) >= 0 } 33 | ?.sortedWith(SizeComparator) 34 | ?: emptyList() 35 | 36 | return supportedPreviewSizes.getOrElse(0) { Size(0, 0) } 37 | } 38 | 39 | /** 40 | * Returns a new SurfaceTexture that will be the target for the camera preview 41 | */ 42 | fun buildTargetTexture( 43 | containerView: TextureView, 44 | characteristics: CameraCharacteristics 45 | ): SurfaceTexture? { 46 | 47 | /*** Codelab --> Change this function to handle viewfinder rotation and scaling ***/ 48 | 49 | val windowSize = Size(containerView.width, containerView.height) 50 | val previewSize = findBestPreviewSize(windowSize, characteristics) 51 | 52 | return containerView.surfaceTexture?.apply { 53 | setDefaultBufferSize(previewSize.width, previewSize.height) 54 | } 55 | } 56 | } 57 | 58 | internal object SizeComparator : Comparator { 59 | override fun compare(a: Size, b: Size): Int { 60 | return b.height * b.width - a.width * a.height 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /step1/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /step1/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /step1/src/main/res/layout/activity_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 24 | 28 | -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step1/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step1/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step1/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | #FFBB86FC 19 | #FF6200EE 20 | #FF3700B3 21 | #FF03DAC5 22 | #FF018786 23 | #FF000000 24 | #FFFFFFFF 25 | -------------------------------------------------------------------------------- /step1/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | Camera2 Codelab 19 | -------------------------------------------------------------------------------- /step1/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 25 | -------------------------------------------------------------------------------- /step2/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /step2/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | apply plugin: 'kotlin-android' 19 | 20 | 21 | android { 22 | compileSdk 34 23 | 24 | defaultConfig { 25 | applicationId "com.example.camera2.preview.step2" 26 | minSdk 24 27 | targetSdk 34 28 | versionCode 1 29 | versionName "1.0" 30 | 31 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 32 | } 33 | 34 | buildTypes { 35 | release { 36 | minifyEnabled false 37 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 38 | } 39 | } 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | kotlinOptions { 45 | jvmTarget = '1.8' 46 | } 47 | buildFeatures { 48 | viewBinding true 49 | } 50 | } 51 | 52 | dependencies { 53 | implementation 'androidx.core:core-ktx:1.12.0' 54 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2' 55 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1' 56 | implementation 'androidx.appcompat:appcompat:1.6.1' 57 | implementation 'com.google.android.material:material:1.10.0' 58 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 59 | testImplementation 'junit:junit:4.13.2' 60 | androidTestImplementation 'androidx.test.ext:junit:1.1.5' 61 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' 62 | } -------------------------------------------------------------------------------- /step2/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /step2/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 21 | 22 | 29 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /step2/src/main/java/com/google/codelab/camera2/CameraActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.codelab.camera2 18 | 19 | import android.Manifest 20 | import android.annotation.SuppressLint 21 | import android.content.Context 22 | import android.content.pm.PackageManager 23 | import android.graphics.SurfaceTexture 24 | import android.hardware.camera2.CameraCaptureSession 25 | import android.hardware.camera2.CameraDevice 26 | import android.hardware.camera2.CameraManager 27 | import android.hardware.display.DisplayManager 28 | import android.os.Bundle 29 | import android.os.Handler 30 | import android.os.HandlerThread 31 | import android.os.Looper 32 | import android.util.Log 33 | import android.view.Display 34 | import android.view.Surface 35 | import android.view.TextureView 36 | import android.view.WindowManager 37 | import androidx.appcompat.app.AppCompatActivity 38 | import androidx.core.app.ActivityCompat 39 | import androidx.lifecycle.lifecycleScope 40 | import com.google.codelab.camera2.databinding.ActivityCameraBinding 41 | import kotlinx.coroutines.Dispatchers 42 | import kotlinx.coroutines.launch 43 | 44 | const val TAG = "CAMERA_ACTIVITY" 45 | const val CAMERA_PERMISSION_REQUEST_CODE = 1992 46 | 47 | open class CameraActivity : AppCompatActivity() { 48 | 49 | /** Main Looper*/ 50 | private val mainLooperHandler = Handler(Looper.getMainLooper()) 51 | 52 | /** [HandlerThread] where all camera operations run */ 53 | private val cameraThread = HandlerThread("MyCameraThread").apply { start() } 54 | 55 | /** [Handler] corresponding to [cameraThread] */ 56 | private val cameraHandler = Handler(cameraThread.looper) 57 | 58 | /** hardcoded back camera*/ 59 | private val cameraID = "0" 60 | 61 | /** Detects, characterizes, and connects to a CameraDevice (used for all camera operations) */ 62 | private val cameraManager: CameraManager by lazy { 63 | applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager 64 | } 65 | 66 | /** The [CameraDevice] that will be opened in this Activity */ 67 | private var cameraDevice: CameraDevice? = null 68 | 69 | /** [Surface] target of the CameraCaptureRequest*/ 70 | private var surface: Surface? = null 71 | 72 | /** Where the camera preview is displayed */ 73 | private lateinit var textureView: TextureView 74 | 75 | private lateinit var binding: ActivityCameraBinding 76 | 77 | /** [DisplayManager] to listen to display changes */ 78 | private val displayManager: DisplayManager by lazy { 79 | applicationContext.getSystemService(DISPLAY_SERVICE) as DisplayManager 80 | } 81 | 82 | /** Keep track of display rotations*/ 83 | private var displayRotation = 0 84 | 85 | override fun onCreate(savedInstanceState: Bundle?) { 86 | super.onCreate(savedInstanceState) 87 | binding = ActivityCameraBinding.inflate(layoutInflater) 88 | setContentView(binding.root) 89 | textureView = binding.textureView 90 | 91 | val windowParams: WindowManager.LayoutParams = window.attributes 92 | windowParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT 93 | window.attributes = windowParams 94 | } 95 | 96 | override fun onStart() { 97 | super.onStart() 98 | openCameraWithPermissionCheck() 99 | } 100 | 101 | override fun onDestroy() { 102 | super.onDestroy() 103 | release() 104 | cameraThread.quitSafely() 105 | } 106 | 107 | private fun openCameraWithPermissionCheck() { 108 | if (ActivityCompat.checkSelfPermission( 109 | this, Manifest.permission.CAMERA 110 | ) == PackageManager.PERMISSION_GRANTED 111 | ) { 112 | openCamera() 113 | } else { 114 | ActivityCompat.requestPermissions( 115 | this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE 116 | ) 117 | } 118 | } 119 | 120 | @SuppressLint("MissingPermission") 121 | override fun onRequestPermissionsResult( 122 | requestCode: Int, 123 | permissions: Array, 124 | grantResults: IntArray 125 | ) { 126 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 127 | if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { 128 | if (grantResults.getOrNull(0) == PackageManager.PERMISSION_GRANTED) { 129 | openCamera() 130 | } else { 131 | finish() 132 | } 133 | } 134 | } 135 | 136 | @SuppressLint("MissingPermission") 137 | private fun openCamera() = lifecycleScope.launch(Dispatchers.Main) { 138 | cameraManager.openCamera(cameraID, cameraStateCallback, cameraHandler) 139 | } 140 | 141 | /** 142 | * Before creating the [CameraCaptureSession] we apply a transformation to the TextureView to 143 | * avoid distortion in the preview 144 | */ 145 | private fun createCaptureSession() { 146 | if (cameraDevice == null || !textureView.isAvailable) return 147 | 148 | val transformedTexture = CameraUtils.buildTargetTexture( 149 | textureView, cameraManager.getCameraCharacteristics(cameraID), 150 | displayManager.getDisplay(Display.DEFAULT_DISPLAY).rotation 151 | ) 152 | 153 | this.surface = Surface(transformedTexture) 154 | try { 155 | cameraDevice?.createCaptureSession( 156 | listOf(surface), sessionStateCallback, cameraHandler 157 | ) 158 | } catch (t: Throwable) { 159 | Log.e(TAG, "Failed to create session.", t) 160 | } 161 | } 162 | 163 | private fun release() { 164 | try { 165 | surface?.release() 166 | cameraDevice?.close() 167 | } catch (t: Throwable) { 168 | Log.e(TAG, "Failed to release resources.", t) 169 | } 170 | } 171 | 172 | override fun onAttachedToWindow() { 173 | super.onAttachedToWindow() 174 | displayManager.registerDisplayListener(displayListener, mainLooperHandler) 175 | } 176 | 177 | override fun onDetachedFromWindow() { 178 | super.onDetachedFromWindow() 179 | displayManager.unregisterDisplayListener(displayListener) 180 | } 181 | 182 | private val displayListener = object : DisplayManager.DisplayListener { 183 | override fun onDisplayAdded(displayId: Int) {} 184 | override fun onDisplayRemoved(displayId: Int) {} 185 | override fun onDisplayChanged(displayId: Int) { 186 | val difference = displayManager.getDisplay(displayId).rotation - displayRotation 187 | displayRotation = displayManager.getDisplay(displayId).rotation 188 | 189 | if (difference == 2 || difference == -2) { 190 | createCaptureSession() 191 | } 192 | } 193 | } 194 | 195 | private val cameraStateCallback = object : CameraDevice.StateCallback() { 196 | override fun onOpened(camera: CameraDevice) { 197 | cameraDevice = camera 198 | try { 199 | mainLooperHandler.post { 200 | if (textureView.isAvailable) { 201 | createCaptureSession() 202 | } 203 | textureView.surfaceTextureListener = surfaceTextureListener 204 | } 205 | } catch (t: Throwable) { 206 | release() 207 | Log.e(TAG, "Failed to initialize camera.", t) 208 | } 209 | } 210 | 211 | override fun onDisconnected(camera: CameraDevice) { 212 | cameraDevice = camera 213 | release() 214 | } 215 | 216 | override fun onError(camera: CameraDevice, error: Int) { 217 | cameraDevice = camera 218 | Log.e(TAG, "on Error: $error") 219 | } 220 | } 221 | 222 | private val sessionStateCallback = object : CameraCaptureSession.StateCallback() { 223 | override fun onConfigured(cameraCaptureSession: CameraCaptureSession) { 224 | try { 225 | val captureRequest = cameraDevice?.createCaptureRequest( 226 | CameraDevice.TEMPLATE_PREVIEW 227 | ) 228 | captureRequest?.addTarget(surface!!) 229 | cameraCaptureSession.setRepeatingRequest( 230 | captureRequest?.build()!!, null, cameraHandler 231 | ) 232 | } catch (t: Throwable) { 233 | Log.e(TAG, "Failed to open camera preview.", t) 234 | } 235 | } 236 | 237 | override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession) { 238 | Log.e(TAG, "Failed to configure camera.") 239 | } 240 | } 241 | 242 | /** 243 | * Every time the size of the TextureSize changes, 244 | * we calculate the scale and create a new session 245 | */ 246 | private val surfaceTextureListener = object : TextureView.SurfaceTextureListener { 247 | override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) { 248 | createCaptureSession() 249 | } 250 | 251 | override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { 252 | createCaptureSession() 253 | } 254 | 255 | override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} 256 | override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = false 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /step2/src/main/java/com/google/codelab/camera2/CameraUtils.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.codelab.camera2 18 | 19 | import android.graphics.Matrix 20 | import android.graphics.SurfaceTexture 21 | import android.hardware.camera2.CameraCharacteristics 22 | import android.util.Size 23 | import android.view.TextureView 24 | import kotlin.math.max 25 | 26 | object CameraUtils { 27 | 28 | /** Return the biggest preview size available which is smaller than the window */ 29 | private fun findBestPreviewSize(windowSize: Size, characteristics: CameraCharacteristics): 30 | Size { 31 | val supportedPreviewSizes: List = 32 | characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) 33 | ?.getOutputSizes(SurfaceTexture::class.java) 34 | ?.filter { SizeComparator.compare(it, windowSize) >= 0 } 35 | ?.sortedWith(SizeComparator) 36 | ?: emptyList() 37 | 38 | return supportedPreviewSizes.getOrElse(0) { Size(0, 0) } 39 | } 40 | 41 | /** 42 | * Computes the relative rotation between the sensor orientation and the display rotation 43 | */ 44 | private fun computeRelativeRotation( 45 | characteristics: CameraCharacteristics, 46 | deviceOrientationDegrees: Int 47 | ): Int { 48 | val sensorOrientationDegrees = 49 | characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 50 | 51 | // Reverse device orientation for front-facing cameras 52 | val sign = if (characteristics.get(CameraCharacteristics.LENS_FACING) == 53 | CameraCharacteristics.LENS_FACING_FRONT 54 | ) 1 else -1 55 | 56 | return (sensorOrientationDegrees - (deviceOrientationDegrees * sign) + 360) % 360 57 | } 58 | 59 | /** 60 | * Returns a new SurfaceTexture with optimized transformation 61 | */ 62 | fun buildTargetTexture( 63 | containerView: TextureView, 64 | characteristics: CameraCharacteristics, 65 | surfaceRotation: Int 66 | ): SurfaceTexture? { 67 | 68 | val surfaceRotationDegrees = surfaceRotation * 90 69 | val windowSize = Size(containerView.width, containerView.height) 70 | val previewSize = findBestPreviewSize(windowSize, characteristics) 71 | val sensorOrientation = 72 | characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 73 | val isRotationRequired = 74 | computeRelativeRotation(characteristics, surfaceRotationDegrees) % 180 != 0 75 | 76 | /* Scale factor required to scale the preview to its original size on the x-axis */ 77 | var scaleX = 1f 78 | /* Scale factor required to scale the preview to its original size on the y-axis */ 79 | var scaleY = 1f 80 | 81 | if (sensorOrientation == 0) { 82 | scaleX = 83 | if (!isRotationRequired) { 84 | windowSize.width.toFloat() / previewSize.height 85 | } else { 86 | windowSize.width.toFloat() / previewSize.width 87 | } 88 | 89 | scaleY = 90 | if (!isRotationRequired) { 91 | windowSize.height.toFloat() / previewSize.width 92 | } else { 93 | windowSize.height.toFloat() / previewSize.height 94 | } 95 | } else { 96 | scaleX = 97 | if (isRotationRequired) { 98 | windowSize.width.toFloat() / previewSize.height 99 | } else { 100 | windowSize.width.toFloat() / previewSize.width 101 | } 102 | 103 | scaleY = 104 | if (isRotationRequired) { 105 | windowSize.height.toFloat() / previewSize.width 106 | } else { 107 | windowSize.height.toFloat() / previewSize.height 108 | } 109 | } 110 | 111 | /* Scale factor required to fit the preview to the TextureView size */ 112 | val finalScale = max(scaleX, scaleY) 113 | val halfWidth = windowSize.width / 2f 114 | val halfHeight = windowSize.height / 2f 115 | 116 | val matrix = Matrix() 117 | 118 | if (isRotationRequired) { 119 | matrix.setScale( 120 | 1 / scaleX * finalScale, 121 | 1 / scaleY * finalScale, 122 | halfWidth, 123 | halfHeight 124 | ) 125 | } else { 126 | matrix.setScale( 127 | windowSize.height / windowSize.width.toFloat() / scaleY * finalScale, 128 | windowSize.width / windowSize.height.toFloat() / scaleX * finalScale, 129 | halfWidth, 130 | halfHeight 131 | ) 132 | } 133 | 134 | // Rotate to compensate display rotation 135 | matrix.postRotate( 136 | -surfaceRotationDegrees.toFloat(), 137 | halfWidth, 138 | halfHeight 139 | ) 140 | 141 | containerView.setTransform(matrix) 142 | 143 | return containerView.surfaceTexture?.apply { 144 | setDefaultBufferSize(previewSize.width, previewSize.height) 145 | } 146 | } 147 | } 148 | 149 | internal object SizeComparator : Comparator { 150 | override fun compare(a: Size, b: Size): Int { 151 | return b.height * b.width - a.width * a.height 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /step2/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /step2/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /step2/src/main/res/layout/activity_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 24 | 28 | -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /step2/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android/codelab-android-camera2-preview/b61062b27cef571a2aae13f6d9e667e2853d9165/step2/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /step2/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | #FFBB86FC 19 | #FF6200EE 20 | #FF3700B3 21 | #FF03DAC5 22 | #FF018786 23 | #FF000000 24 | #FFFFFFFF 25 | -------------------------------------------------------------------------------- /step2/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | Camera2 Codelab 19 | -------------------------------------------------------------------------------- /step2/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 25 | --------------------------------------------------------------------------------