How To Make A Camera App In Android Studio
How to Make Your Own Android Photographic camera App without Knowing How
Weird title? Aye, you won't be learning how-to do 10 if you already know how.
This mail is inspired by a contempo attempt I made to build an app for scanning texts (characters) in images. I am kind of an abet of learning by doing and so I decided to put up a tutorial for any Android beginners looking to build a simple app that does some very common tasks.
If yous are learning Android development, already accept Android Studio setup you should exist able to follow along.
I didn't include detailed description of the code included in this post in other to proceed to mail brusk. Experience free to check the codelab linked in the post to learn more about the code.
Getting Started
CameraX is a member of the Jetpack library family that helps android developers use device camera feature with minimum worries about compatibility. If you lot are new to Android development.
AndroidX mostly (in my own words) is a set up of libraries that enable developer use new features without worrying besides much about support for older versions of Android Bone. Previously known as Back up Library.
In this postal service, y'all volition acquire how to build a unproblematic Camera App using Jetpack's CameraX library.
Pre-requisites
To follow along, you will need the post-obit:
- Android Studio 3.six+
two. Beginner level cognition of Android Development
3. Android Phone or Emulator
Now allow'southward dive into creating the Camera App.
Creating a New Project
Let'due south create a new project in Android studio. To do this, open Android Studio and then click file > new > new projection.
Alternatively, you can start a new project from Android Studio's welcome screen.
Next, follow the new project wizard to complete the process.
Tip: To follow along better, delight select "empty activity" in the project template window.
Hit next when you lot are done selecting a template to move to the new projection configuration window. You tin specify the name for your new Camera app, the parcel proper noun and the location on your computer where the project will be saved.
Tip: I recommend you continue Language, Minimum SDK and the Utilize legacy android.support.libraries default (do not alter the default values).
Side by side, click Finish and wait for Android Studio to finish setting up your project.
Add CameraX to Project
At this point, we have successfully set up our new project. One last step before we start coding the app, allow's add the Camerax library to our project.
To do that, open up the app-level build.gradle file and add the following code to the dependency block:
// CameraX core library using camera2 implementation
implementation "androidx.camera:photographic camera-camera2:$camerax_version"
// CameraX Lifecycle Library
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha14"
Still in the app-level build.gradle file, add the following code to the android cake just after buildTypes section:
compileOptions {
sourceCompatibility JavaVersion. VERSION_1_8
targetCompatibility JavaVersion. VERSION_1_8
}
Sync Gradle past clicking Sync Now on the top yellow bar.
The rest of this tutorial volition include code establish on the official codelab for CameraX.
Add Required Permission
In order for your app to use the device camera (hardware), you'll need to specify in your app's manifest file that information technology uses the camera. Add the post-obit code to AndroidManifest.xml (located in project directory/app/src/main):
<uses-characteristic android:name="android.hardware.camera.whatever" />
<uses-permission android:proper name="android.permission.Photographic camera" />
The code should be pasted only to a higher place the application tag.
Coding the Layout
Now that we take CameraX in our project and the required permission configuration is washed, lets lawmaking the Graphical User Interface (GUI) for our Camera App. The GUI volition incorporate a CameraX Perview window and a shoot push. It looks something similar this:
So, lets write the lawmaking. Open up the activity_main.xml and paste the post-obit code within the root constraint layout:
<Push button
android:id="@+id/camera_capture_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="50dp"
android:scaleType="fitCenter"
android:text="Take Photo"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:elevation="2dp" /><androidx.camera.view.PreviewView
android:id="@+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
With that, nosotros are done with our GUI. Feel free to add some more creativity it every bit that might be very of import if you plan to show off your app to friends :).
Coding the Camera Logic
In the final section, we wrote all the code required to add CameraX to our layout file. Now lets write the lawmaking that controls how the actual app works.
We'll write all our lawmaking in MainActivity.kt. Open the file and add the following code:
Paste the following code merely above the onCreate method:
private var imageCapture: ImageCapture? = zeroprivate lateinit var
outputDirectory: File
private lateinit var cameraExecutor: ExecutorService
If you are familiar with OOP, you might be able to become that the code above is annunciation for fields.
Next, move just below the onCreate method and paste the following:
private fun takePhoto() {
// Go a stable reference of the modifiable image capture apply case
val imageCapture = imageCapture ?: return // Create time-stamped output file to hold the image
val photoFile = File(
outputDirectory,
SimpleDateFormat(FILENAME_FORMAT, Locale.US
).format(System.currentTimeMillis()) + ".jpg") // Create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
// Set image capture listener, which is triggered after photograph has
// been taken
imageCapture.takePicture(
outputOptions, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
Log.e(TAG, "Photo capture failed: ${exc.bulletin}", exc)
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
val msg = "Photo capture succeeded: $savedUri"
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
}
})
}
The code above adds a takePhoto() method. Just as the name of the method, calling the method volition accept a photo.
Now paste the post-obit lawmaking below the takePhoto() method:
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener(Runnable {
// Used to bind the lifecycle of cameras to the lifecycle owner
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
// Preview
val preview = Preview.Architect()
.build()
.also {
information technology.setSurfaceProvider(viewFinder.createSurfaceProvider())
} imageCapture
= ImageCapture.Builder()
.build()
// Select back photographic camera as a default
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try {
// Unbind apply cases before rebinding
cameraProvider.unbindAll()
// Demark use cases to camera
cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture)
} catch(exc: Exception) {
Log.e(TAG, "Use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(this))
}
The code adds a startCamera method which starts the photographic camera.
We will demand to add lawmaking to request/verify that the necessary permissions have been granted. Let'due south practise that past adding the following code below the startCamera() method.
private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
ContextCompat.checkSelfPermission(
baseContext, it) == PackageManager.PERMISSION_GRANTED
}@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
individual fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(information technology, resources.getString(R.string.app_name)).employ { mkdirs() } }
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
} override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults:
IntArray) {
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (allPermissionsGranted()) {
startCamera()
} else {
Toast.makeText(this,
"Permissions not granted by the user.",
Toast.LENGTH_SHORT).evidence()
cease()
}
}
}
The code above also includes logic for getting storage output directory.
Finally, paste the following lawmaking at the end of the last code:
override fun onDestroy() {
super.onDestroy()
cameraExecutor.shutdown()
} companion object {
private const val TAG = "CameraXBasic"
private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
private const val REQUEST_CODE_PERMISSIONS = ten
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.Camera)
}
In onDestroy, we practice some cleanup by closing the camera. the total content of MainActivity.kt should wait like this:
Running the App
If y'all got to this bespeak without whatsoever errors, Congrats!!!! Hit the green play button in Android Studio to run your app on an emulator or physical android device.
Conclusion
We've been able to walk through creating a new Android Studio project, add together CameraX to the project and we used CameraX to build a small camera app.
The app doesn't do much and as it is at the end of this post it's the exaclt copy of the sample app in the CameraX codelab. To brand the app truely yours, feel free to customise the GUI and add together some more features. Add features you will dear to see in your ideal camera app. That is all from me for at present. You tin find the official CameraX codelab hither
Source: https://aboyi.medium.com/how-to-make-your-own-android-camera-app-without-knowing-how-aca3364358b
Posted by: mcdonaldyone1997.blogspot.com
0 Response to "How To Make A Camera App In Android Studio"
Post a Comment