How to work with cameras on Android devices in two ways
14 minute(s) read
|
Published on: Apr 29, 2021
Updated on: Dec 14, 2021
|
Cameras can be used to photograph, scan different types of barcodes, or even barcodes on bills. It should be noted that the Camera is a piece of hardware placed inside phones or other devices, and also, to use it, you need software that is installed and defined inside the phone system so that it can be hard. Used the software for the required things. In this part of the tutorial, we want to talk about setting up and using the existing camera software.
The methods used to use the camcorder in Android systems are as follows:
1- Using an interface program:
Using the interface program, you can use the camera software and record your photo, then transfer it to another application to get the required output.
2- Using API:
This method uses the camcorder software and the API inside the system directly and without any interface.
Sometimes we use the default camcorder directly in the system to take photos or record video, which is the second method of setting up the camcorder. In this method, the APIs are used directly and without any interface. We do. In this method, photography and video recording are done in the same camcorder environment, and photos and videos are stored in the same environment. There is no need to transfer them to another application and program.
In this part of the tutorial, we want to do the first method, and in fact, we have nothing to do with the second method, which takes photos and records videos in the same environment. In the continuation of this tutorial, I will do the second method.
1- We create a new project in Android Studio and choose its name as desired. The name of the project we have chosen in this tutorial is Camera.
2- The type of activity we need in this project is Blank Activity. It is better to choose an activity of this type.
3- We need to create the user interface, and in this user interface, we need a Button and ImageView.
4- Add a uses-feature tag to the project as follows:
By entering the above code in the project, I also mention to all virtual stores such as Google Play that android. Hardware. Camcorder must exist, and the existence of this is essential for the application's performance. If devices do not support this feature, they will not be displayed in the application list.
The code that should be in the AndroidManifest.xml section is as follows:
Note:
In this section, we do not need to get permission to use the camcorder because we use a side program. It is necessary to get a license from the Camera when we want to use the main and default system camcorder directly and using the API, in other words, in the continuation of this tutorial, which we will do in a second way, we must have a license.
5- We edit the activity layout as follows:
By entering the above code, we add an ImageView with the imageView ID and a Button with the btn_photo ID for the project.
6- We define two widgets in the layout of the Java file.
7- The codes that should be in the MainActivity.java section are as follows:
8- Inside the onCreate method for the btnPhoto defined button, I define an event of type setOnClickListener to launch the camera app by clicking or touching the page and the corresponding icon.
I use the MediaStore to communicate between the Camera and the app that will generate the output and show it to us. The output that we will receive can be in the form of photos, videos, or even audio. In this part of the tutorial, we need a photo output.
Note:
MediaStore is a subset of android. Provider.
We use ACTION_IMAGE_CAPTURE because the action we want to take is to take a photo and send it as output to another application.
I create an int variable with the desired name CameraRequest in the activity class and give it a value of 1:
protected static final int CameraRequest = 1;
This variable should only be called in this class, so we should define it as protected static final. It should be noted that its value should be constant and not change.
So far, we have made changes that the user can move from the application to the application's activity where the output is to be taken by clicking or pressing a button.
The code that should be in the MainActivity.java section is as follows:
The next step is to transfer the image data to the application and put it in ImageView.
After the onCreate () method in the MainActivity class, I add the onActivityResult () method, as follows:
The onActivityResult () method is unlike onCreate () and will be executed when transferred from one activity to another. Note that the onCreate () method also executes when creating an activity. After the user takes a picture using the camcorder and then is directed to the program's main activity, all the code inside the onActivityResult () is executed.
The onActivityResult () method has three parameters resultCode, requestCode, and data, which in this part of the tutorial, we will work with the first and third parameters.
In the code above, we first define a condition to check if the contents of the requestCode execute the code inside the block with CameraRequest.
The codes inserted inside the requestCode are previously added to the camcorder activity by the startActivityForResult () method in onCreate () and are now received by the onActivityResult.
It should be noted that the image we will receive must be converted to Bitmap data type so that we can easily display it in ImageView. For this reason, we create a Bitmap object with the desired name resultPhoto, which receives and stores all the received information using get data. Then, using setImageBitmap, the received data is placed inside ImageView and displayed.
9- I run the project.
After running the project, we will see an ImageView output with a default image. Default ic_launcher_background image inside the drawable folder. It also has a Button.
10- I click or touch the button.
11- We are transferred to the camera screen, then we capture an image.
The complete code to be included in the MainActivity.java section is as follows:
It should be noted that we may use a device on which the Camera is not installed and active, so when pressing the Take photo button does not take a picture or so-called crash. To prevent this and manage and fix this error, Take the necessary measures.
For this purpose, we also put the Try catch command inside the activity codes:
Entering the above code and adding the try-catch commands will execute the startActivityForResult method, which is the same code inserted inside the try. If you want to get the desired result, to find the active Camera in the device, open the Camera like the previous section. But if it cannot find the Camera, the commands written in the catch section will be executed, and we will also define a Toast message here.
Note:
ActivityNotFoundException is used to manage errors other than not finding activity.
The code that should be included in the MainActivity.java section is as follows:
The second method of working with the camcorder
In the previous part and the posts above, I discussed how to use the Camera and photography and the default program available on the device. It was transferred to manage the Camera, and then the result and output were transferred to another application.
It is worth mentioning that in this part of the tutorial, you will also learn how to use the Camera2 API, which connects directly to the program and the Camera without the need for an interface and does not leave the program to perform photo or video recording processes.
The working procedure of this method is that it uses the Camera that is installed directly on the device and does not use any other side program. The process of taking photos and recording videos is done directly.
What are the advantages of Camera2 API over Camera API?
- They are better and more compatible with new hardware, which leads to high-quality outputs.
- It is possible to apply effects and filters to the Camera.
- It is possible to get a list of all available cameras using getCameraIdList.
- It is possible to obtain the specifications of different types of cameras using CameraCharacteristics.
- Taking photos can be done at a higher speed and higher quality.
In this part of the tutorial, we want to create a project that can directly communicate without any interface and interface that can communicate by touching or clicking the camera icon and save the output in the device itself by taking a picture or recording a video. Slow and do not transfer to another application.
1- I will create a new project and select its name Camera2 API as desired.
2- It is worth mentioning that when creating a project, be careful in choosing an activity because we have to create the project with Empty Activity and Minimum API 21.
3- The language required for this project is Java.
4- In the first steps, we must have permissions from the device camera. As we said before, we can use peripherals to do this. In this case,, you do not need to have a license from the Camera, but if we want to use the device's main Camera, we must receive permissions.
The codes listed above have three licenses that we have defined. And the first two licenses are for access permissions for the device camera, and the third license is for access to the device memory.
The code that should be in the AndroidManifest.xml section is as follows:
We need to edit the activity layout to have a View and a Button, a Button to capture images, and a View to display the Camera.
To output and content received from the Camera, we use Camera Preview from TextureView. We also use TextureView to display live video content.
The code that should be included in activity_main.xml is as follows:
In this section, we disable the toolbar. After all, we do not need it because we want to dedicate more of the screen to TextureView. That's why we're changing the existing default theme style to NoActionBar to remove the toolbar.
The code that should be in the styles.xml section is as follows:
I define the required methods in MainActivity:
We defined the TextureView and Button widgets inside the onCreate method in the code above.
We need a Listener to communicate between the camcorder and TextureView.
Create a TextureView.SurfaceTextureListener method called textureListener:
This method we have defined has four functions:
- onSurfaceTextureDestroyed
- onSurfaceTextureSizeChanged
- onSurfaceTextureAvailable
- onSurfaceTextureUpdated
The use of each of these functions is based on their naming.
By running the activity, the onSurfaceTextureAvailable method is also executed. At this moment, it is necessary to activate the Camera so that the user can record a photo, and its output can be displayed through the device itself. To do this, we add a new method called openTheCamera to this function and put the code inside it that is related to the camera information:
12- Put the openTheCamera method inactivity after the TextureView.SurfaceTextureListener method.
The complete codes that should be included in the activity are as follows:
In the code above, we create an object of the CameraManager class called camManager, used to manage cameras.
The getCameraIdList method returns the camera IDs on the device.
GetOutputSizes can get the image size received as output from the Camera.
We can use the openCamera method to communicate with the camcorder, which should be noted that this method has three parameters:
The first parameter is cameraId, used to store the camera ID.
The second stateCallBack parameter can be used to get the camcorder's status.
The third parameter is a controller that has received a null value in this section.
If you follow all the steps and steps in this section carefully, you will encounter a problem due to non-compliance with an exception.
The problem is with the getCameraIdList section, which consists of two modes:
In the first case, CameraManager cannot open the Camera.
And in the second case, it occurs when the connection between the Camera and the program is disconnected for any reason and is not established.
Hover your mouse over getCameraIdList and press alt + Enter to solve this problem.
There are two ways to solve this problem:
Solution 1:
The CameraAccessException exception is defined in the method title by selecting Add exception to the method signature.
private void openTheCamera () throws CameraAccessException {throw
Solution 2:
Put getCameraIdList inside try-catch to fix the problem.
The result of solving this problem will be as follows:
13- Now, we create the second parameter of openCamera called camStateCallback.
14- How to make this parameter is as follows:
The following are three camera situations that we must manage:
onOpened:
When the Camera is open and communicating.
onDisconnected:
When the Camera is disconnected.
onError:
When an error occurs.
15- Complete and edit camStateCallBack as follows:
In the codes listed above, the onOpened method has a parameter of type CameraDevice called cameraDevice.
To create the createCameraPreview method, place the mouse pointer on it and press the alt + Enter keys. Then select the create method option and then select MainActivity:
Complete the created method as follows:
It should be noted that after defining the second parameter, StateCallback, a problem arises that to solve it, we must also define the sinister parameter to be solved. Like the following:
In this part of the tutorial, you will learn two ways to use the cameras on the devices. The first method was to use peripherals to take photos or record video, and the second method was to use the Camera directly on the device.
We have mentioned the important points in both methods that you must pay attention to.
Follow all the steps step by step and with high accuracy, and if you encounter a problem, go through the step again from the beginning.
After passing this training course, you can easily use two methods to use the Camera, take photos and record video using the device's Camera or peripherals.
About our Android and iOS app development services