[Android] 20.3 camera and video recording, androidprop 3
Category: C #, Android, VS2015;
Date created: 1. Introduction
The Camera provided by Android has two typical versions: one is provided before Android 5.0, called Camera; the other is provided from Android 5.0, called Camera2.
Here, we only demonstrate how to use the system Camera program to take photos. Ii. Basic concepts of Camera
There are two ways to achieve the Camera and Camera functions using Camera:
First, you can directly use Intent to start the built-in Camera App to enable the Camera and Camera functions, and then use Android. under the Provider namespace. mediaStore class obtains the file path for storing the photo or video results. This is the simplest way to achieve it, and can basically meet general requirements.
The second is to use the Camera API to customize the Camera to implement the special Camera and Camera functions.
1. Determine whether to declare the camera in AndroidMainfest. xml.
(1) Camera permissions and Camera features
If you are calling the System Camera program, you do not need to declare this permission and feature.
If you are constructing a custom Camera program, you must declare the permission to use the Camera in AndroidMainfest. xml, for example:
<Uses-permission android: name = "android. permission. CAMERA"/>
You must also declare the camera features in AndroidMainfest. xml, for example:
<Uses-feature android: name = "android. hardware. camera"/>
If your program may need to use a camera, but it is not necessary to use it, you can set the android: required attribute, for example:
<Uses-feature android: name = "android. hardware. camera" android: required = "false"/>
(2) Storage Permissions
To store your photos or videos on an extended storage device (such as an SD card), you must declare the following permissions:
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
(3) audio recording permission
To record audio or video, you must set the following permissions in the AndroidMainfest. xml file:
<Uses-permission android: name = "android. permission. RECORD_AUDIO"/>
2. Use the System Camera program
This is a method that allows your program to be encoded with the least amount, and then you can use the Camera quickly. In this way, you can use an Intent to call the system's Camera program, let the system's Camera application take photos or record videos, and return the shooting or recording results to your own application.
(1) Basic usage
(A) construct a Camera Intent-create an Intent for taking a photo or video. You can use either of the following methods:
Request the System Camera program to take an image. For example:
Intent intent = new Intent (MediaStore. ActionImageCapture );
Request the System Camera program to record a video. For example:
Intent intent = new Intent (MediaStore. ActionVideoCapture );
(B) Enable Camera intent -- execute Camera intent by calling startActivityForResult (). After you call this method, the system Camera program appears on the user interface, then you can take photos or videos.
(C) Receive Intent results -- create an OnActivityResult () method in your application to receive execution results from the System Camera program. This method is called when a user takes a photo or video (or perhaps cancels the shooting operation.
(2) Intent
Using the system Camera to take pictures is the fastest speed and the least Code, allowing your program to take pictures. The intent of an image can contain the following extended information:
(A) MediaStore. ExtraOutput -- specifies a Uri object. The system Camera program stores the captured image to the specified position. This setting is generally highly recommended. If you do not specify this Uri path, the system Camera program stores the image in a default location with a default name. We can get this value through the returned intent and the Intent. GetData () method.
For example:
Private File file;
String dirPath;
String filePath;
......
Intent imageIntent = new Intent (MediaStore. ActionImageCapture );
FilePath = dirPath + $ "/PP {System. DateTime. Now: yyyyMMdd_hhmmss}.jpg ";
File = new File (filePath );
ImageIntent. PutExtra (MediaStore. ExtraOutput, Uri. FromFile (file ));
StartActivityForResult (imageIntent, 100, savedInstanceState );
After the StartActivityForResult () method is executed, you will see the system's Camera interface. After taking a photo (or canceling the photo), the user interface will return your own application. You must intercept the OnActivityResult method to receive execution results and continue the logic of your own code.
(3) Video Recording intent
Using the system Camera to record videos is the fastest speed and the least Code, allowing your program to record videos. The intent of a video recording can contain the following extended information:
MediaStore. ExtraOutput -- specifies a Uri object. The system Camera program stores the recorded video to the specified location. This setting is generally highly recommended. If you do not specify this Uri path, the system Camera program stores the video in the default location with a default name. You can use the returned intent and the Intent. GetData () method to obtain this value.
MediaStore. ExtraVideoQuality-video quality, 0 (low quality, small files for video storage), 1 (high-quality, large files for video storage)
MediaStore. ExtraDurationLimit -- sets a value to limit the video recording time, in seconds.
MediaStore. ExtraSizeLimit -- sets a value to limit the video size, in bytes.
After the StartActivityForResult () method is executed, you will see the system's Camera interface. After you finish recording a video (or cancel shooting), the user interface will return your own application. Then you will receive the execution result through the OnActivityResult () method that you rewrite.
(4) receive results returned by Camera
Once you have taken an intent image or video, you can rewrite the OnActivityResult () method to receive the execution result. After the results are obtained, the images or Videos stored in the specified position can be used by our program.
3. Construct a custom Camera program
Although calling the system Camera App to implement the Camera and Camera functions can meet our simple needs, after all, the degree of freedom is reduced, and the Camera interface is what the system provides.
If you want to customize a pretty interface, you can customize the Camera application to customize the Camera program, which may require more code than calling the system's Camera, however, this can bring different user experiences to your users. For example, the Camera 360 software needs to compile its own program based on the Camera API provided by the SDK.
Note: The Android. Hardware. Camera class provided in versions earlier than 5.0 has been discarded. Instead, the Android. Hardware. Camera class is implemented using Camera2. For details about its usage, see related documents. 2. simulator settings
Because the mobile phone comes with a camera, you can directly use the camera function. However, if you want to test your program in the simulator, you can use the Front Camera to simulate it in the simulator.
Is the simulator parameter setting interface of Android 4.4.2 (Api 19:
After you set "Front Camera" to "Emulated" on this page, the simulator uses a random rectangle to simulate the Camera's photo and video effects.
Is the simulator parameter setting interface of Android 6.0 (Api 23:
Iii. Example
When running in the simulator, open the camera, click the circle button below to take a photo, and save the photo results to the folder specified in the SD card, the image is immediately displayed in the ImageView control. You can also use the image library program that comes with the Android system to view the photo results.
1. Run
The initial Page is displayed on the left and the photo page is displayed on the right.
On the left side is the result of clicking the circular button, and on the right side is the position where the file is saved.
The following picture shows the result after clicking [Video Recording], and the right picture shows the result after recording.
2. Design Steps
(1) Permission requirements
In this example, the following permissions must be added to AndroidManifest. xml:
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
If you already have the corresponding permissions, you do not need to add them again. If you do not have the permissions, double-click the Properties folder and check this permission so that the system will automatically add it to AndroidManifest. xml file, or directly add it to AndroidManifest. xml file.
(2) Add ch2003Main. axml
<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <Button android: id = "@ + id/ch2003_btn1" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = ""/> <Button android: id = "@ + id/ch2003_btn2" android: layout_width = "fill_parent" android: layout_height = "Wrap_content" android: text = "video recording"/> <TextView android: text = "" android: textAppearance = "? Android: attr/textAppearanceSmall "android: layout_width =" match_parent "android: layout_height =" wrap_content "android: id =" @ + id/ch2003_textView1 "/> <ImageView android: src = "@ android: drawable/ic_menu_gallery" android: layout_width = "fill_parent" android: layout_height = "300dp" android: id = "@ + id/ch2003_imageView1" android: adjustViewBounds = "true"/> <VideoView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: id = "@ + id/ch2003_videoView1"/> </LinearLayout
(3) add ch2003BitmapHelpers. cs
The file automatically scales the image to adapt to the screen size. This is to solve the problem that loading the large image directly when the memory is insufficient may cause the application to crash.
using Android.Widget;using Android.Graphics.Drawables;using Android.Graphics;namespace MyDemos.SrcDemos{ public static class ch2003BitmapHelpers { public static void RecycleBitmap(ImageView imageView) { if (imageView == null) { return; } Drawable toRecycle = imageView.Drawable; if (toRecycle != null) { ((BitmapDrawable)toRecycle).Bitmap.Recycle(); } } public static Bitmap LoadAndResizeBitmap(string fileName, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options { InPurgeable = true, InJustDecodeBounds = true }; BitmapFactory.DecodeFile(fileName, options); int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > height || outWidth > width) { if(outWidth > outHeight) { inSampleSize = outHeight / height; } else { inSampleSize = outWidth / width; } } options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options); return resizedBitmap; } }}
(4) add ch2003MainActivity. cs
Using System. collections. generic; using Android. app; using Android. content; using Android. OS; using Android. runtime; using Android. widget; using Android. provider; using Android. content. PM; using Android. graphics; using Android. net; using Java. IO; namespace MyDemos. srcDemos {[Activity (Label = "ch2003MainActivity")] [IntentFilter (new [] {Intent. actionMain}, Categories = new [] {Intent. categoryDefault, ch. myDem OsCategory})] public class ch2003MainActivity: Activity {private File file; string dirPath; string filePath; private ImageView imageView1; private VideoView videoView1; private TextView textView1; private MediaType mediaType; protected override void OnCreate (Bundle savedInstanceState) {base. onCreate (savedInstanceState); SetContentView (Resource. layout. ch2003Main); textView1 = FindViewById <TextV Iew> (Resource. id. ch2003_textView1); imageView1 = FindViewById <ImageView> (Resource. id. ch2003_imageView1); videoView1 = FindViewById <VideoView> (Resource. id. ch2003_videoView1); Button btn1 = FindViewById <Button> (Resource. id. ch2003_btn1); Button btn2 = FindViewById <Button> (Resource. id. ch2003_btn2); // determines whether the camera is available (whether an App is preparing to take a photo) if (IsThereAnAppToTakePictures () {dirPath = $ "{Environment. externalStorageD Irectory. Path}/{Environment. DirectoryPictures}/MyDemosPictures "; if (! System. IO. directory. exists (dirPath) {System. IO. directory. createDirectory (dirPath);} btn1.Click + = delegate {// photograph mediaType = MediaType. image; Intent imageIntent = new Intent (MediaStore. actionImageCapture); filePath = dirPath + $ "/PP {System. dateTime. now: yyyyMMdd_hhmmss}.jpg "; file = new File (filePath); imageIntent. putExtra (MediaStore. extraOutput, Uri. fromFile (file); StartActivityForResult (image Intent, 100) ;}; btn2.Click + = delegate {// video recording mediaType = MediaType. video; Intent videoIntent = new Intent (MediaStore. actionVideoCapture); filePath = dirPath + $ "/PP {System. dateTime. now: yyyyMMdd_hhmmss}.mp4 "; file = new File (filePath); videoIntent. putExtra (MediaStore. extraOutput, Uri. fromFile (file); videoIntent. putExtra (MediaStore. extraVideoQuality, 1); StartActivityForResult (videoIntent, 200) ;};} Else {// if the camera is unavailable, disable the button btn1.Text = "the camera is unavailable and cannot be taken"; btn2.Text = "the camera is unavailable and cannot be recorded "; btn1.Enabled = btn2.Enabled = false ;}/// <summary> // determine whether the camera is available (whether an App is preparing to take a photo) /// </summary> /// <returns> </returns> private bool IsThereAnAppToTakePictures () {Intent intent = new Intent (MediaStore. actionImageCapture); IList <ResolveInfo> availableActivities = PackageManager. queryIntentActivities (intent, Packa GeInfoFlags. MatchDefaultOnly); return availableActivities! = Null & availableActivities. count> 0;} protected override void OnActivityResult (int requestCode, [GeneratedEnum] Result resultCode, Intent data) {base. onActivityResult (requestCode, resultCode, data); // make it available in the image library, that is, when you browse the image library, you can see the photo taken by the camera Intent mediaScanIntent = new Intent (Intent. actionMediaScannerScanFile); Uri contentUri = Uri. fromFile (file); mediaScanIntent. setData (contentUri); SendBroadcast (media ScanIntent); if (mediaType = MediaType. image) {imageView1.Visibility = Android. views. viewStates. visible; videoView1.Visibility = Android. views. viewStates. gone; // Helper Program (ch2003BitmapHelpers. cs) automatically scales the image to fit the screen size. Int width = Resources. displayMetrics. widthPixels; int height = imageView1.Height; using (Bitmap bitmap = ch2003BitmapHelpers. loadAndResizeBitmap (filePath, width, height) {ch2003BitmapHelpers. recycleBitmap (imageView1); imageView1.SetImageBitmap (bitmap); imageView1.RefreshDrawableState ();} textView1.Text = "photo result: \ n" + filePath;} else {imageView1.Visibility = Android. views. viewStates. gone; videoView1.Visibility = Android. views. viewStates. visible; videoView1.SetVideoURI (Uri. parse (filePath); videoView1.SetMediaController (new MediaController (this); videoView1.Start (); textView1.Text = "Video Recording result: \ n" + filePath ;}}}}