Hướng dẫn code mở camera trên android

• Bước 2: Sau tiến hành mở phần mềm bạn sẽ thấy dòng chữ : “ DMSS muốn tìm kiếm và kết nối với các thiết bị trên mạng cục bộ của bạn” bạn hãy bấm “OK”. Tiếp đến bạn sẽ thấy dòng chữ “ DMSS muốn gửi thông báo cho bạn” bạn hãy bấm vào chữ “cho phép” thì phần mềm sẽ gửi thông báo cho bạn khi có cảnh báo. Sau đó nhấn ENTER để bắt đầu.

• Bước 3: Tiếp đến bạn sẽ chọn khu vực hoặc quốc gia nơi bạn sinh sống và lắp đặt.

Hướng dẫn code mở camera trên android
• Bước 4: Nếu bạn đang sử dụng phần mềm iDMSS Lite/ Plus muốn chuyển sang dùng phần mềm DMSS mới, sẽ có một video hướng dẫn bạn cách sao lưu các thiết bị từ phần mềm cũ để chuyển sang phần mềm mới một cách chi tiết.

Đầu tiên mở phần mềm Idmss chọn vào quản lý thiết bị -> chọn khởi tạo thiết bị -> chọn tất cả cái thiết bị trong phần mềm cũ -> chọn lại khởi tạo thiết bị 1 lần nữa sẽ tạo tra 1 hình QR code

Chọn lưu lại để sử dụng trong phần mềm DMSS

Hướng dẫn code mở camera trên android

2. THÊM THIẾT BỊ VÀO PHẦN MỀM DMSS:

2.1 Thêm vào bằng QR code: có thể thêm thiết bị bằng QR code(1) được in trên sản phẩm hoặc có thể thêm các thiết bị từ phần mềm idmss cũ được xuất ra từ bước trên

2.2. Thêm bằng địa chỉ ip hoặc tên miền của thiết bị:chọn vào + -> chọn địa chỉ IP/ tên miền -> chọn thiết bị cần thêm

Camera là một thiết bị cho phép bạn chụp hình hoặc quay video. Trong Android có 2 cách để bạn làm việc với Camera.

Cách 1:

Trên hệ điều hành Android đã có sẵn ứng dụng để làm việc với Camera, ứng dụng của bạn có thể gọi ứng dụng đó thông qua một Intent không tường minh (Implicit Intent) để yêu cầu một hành động nào đó với Camera, chẳng hạn yêu cầu mở Camera và chụp ảnh, hoặc yêu cầu mở Camera để quay video, và sau đó nhận kết quả trả về.

Cách 2:

Android cung cấp cho bạn các API để làm việc trực tiếp với Camera.

Với Android Level < 21 bạn có thể làm việc trực tiếp với Camera thông qua class android.hardware.Camera, tuy nhiên class này đã lỗi thời (Deprected) và không còn được sử dụng trong Android Level >= 21, khuyến cáo bạn nên sử dụng Camera2 API.

Hướng dẫn code mở camera trên android

Trong tài liệu này tôi sẽ hướng dẫn bạn sử dụng Intent không tường minh để gọi vào ứng dụng Camera có sẵn trong hệ thống yêu cầu mở Camera để chụp hình hoặc quay video.

Bạn có thể xem hướng dẫn sử dụng Camera2 API tại:
  • Android Camera API2

2. Tổng quan

Trên hệ điều hành Android đã có sẵn ứng dụng để làm việc với Camera, trên ứng dụng của bạn có thể tạo một Intent không tường minh (implicit intent) để gọi tới ứng dụng này, yêu cầu mở Camera để quay phim hoặc chụp hình.

// Tạo một Intent không tường minh,
// để yêu cầu hệ thống mở Camera chuẩn bị chụp hình.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
int REQUEST_ID_IMAGE_CAPTURE = 100;
// Start Activity chụp hình, và chờ đợi kết quả trả về.
this.startActivityForResult(intent, REQUEST_ID_IMAGE_CAPTURE);

Các loại Intent cho Camera:

Loại Intent

Mô tả

ACTION_IMAGE_CAPTURE_SECURE

Nó sẽ trả về một Image được chụp từ Camera, khi thiết bị được bảo mật

ACTION_VIDEO_CAPTURE

Nó sẽ gọi một ứng dụng video trong Android để quay video từ Camera.

EXTRA_SCREEN_ORIENTATION

Sử dụng để sét đặt chiều của màn hình là "vertical" hoặc "landscape"

EXTRA_FULL_SCREEN

Nó được sử dụng để điều khiển giao diện người dùng của ViewImage

INTENT_ACTION_VIDEO_CAMERA

Sử dụng để khởi động Camera ở chế độ quay video.

EXTRA_SIZE_LIMIT

Sử dụng để chỉ định giá trị lớn nhất cho kích thước file ảnh và video.

Trong trường hợp bạn muốn lưu trữ ảnh chụp hoặc video vừa quay được trên thiết bị bạn cần cấu hình cho phép đọc và ghi dữ liệu vào thiết bị. Cấu hình trên AndroidManifest.xml.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Với Android Level >= 23, bạn cần phải sử dụng code để hỏi người dùng cho phép đọc và ghi dữ liệu vào thiết bị.

// Với Android Level >= 23 bạn phải hỏi người dùng cho phép ghi dữ liệu vào thiết bị.
if (android.os.Build.VERSION.SDK_INT >= 23) {
   // Kiểm tra quyền đọc/ghi dữ liệu vào thiết bị lưu trữ ngoài.
   int readPermission = ActivityCompat.checkSelfPermission(this,
                                  Manifest.permission.READ_EXTERNAL_STORAGE);
   int writePermission = ActivityCompat.checkSelfPermission(this,
                                  Manifest.permission.WRITE_EXTERNAL_STORAGE);
 if (writePermission != PackageManager.PERMISSION_GRANTED ||
         readPermission != PackageManager.PERMISSION_GRANTED) {
     // Nếu không có quyền, cần nhắc người dùng cho phép.
     this.requestPermissions(
             new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                     Manifest.permission.READ_EXTERNAL_STORAGE},
             REQUEST_ID_READ_WRITE_PERMISSION
     );
 }
}

Hướng dẫn code mở camera trên android

Xử lý khi người dùng trả lời yêu cầu.

// Khi yêu cầu hỏi người dùng được trả về (Chấp nhận hoặc không chấp nhận).
@Override
public void onRequestPermissionsResult(int requestCode,
                                  String permissions[], int[] grantResults) {
   super.onRequestPermissionsResult(requestCode, permissions, grantResults);
   //
   switch (requestCode) {
       case REQUEST_ID_READ_WRITE_PERMISSION: {
           // Chú ý: Nếu yêu cầu bị hủy, mảng kết quả trả về là rỗng.
           // Người dùng đã cấp quyền (đọc/ghi).
           if (grantResults.length > 1
                   && grantResults[0] == PackageManager.PERMISSION_GRANTED
                   && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
               Toast.makeText(this, "Permission granted!", Toast.LENGTH_LONG).show();
               this.captureVideo();
           }
           // Hủy bỏ hoặc bị từ chối.
           else {
               Toast.makeText(this, "Permission denied!", Toast.LENGTH_LONG).show();
           }
           break;
       }
   }
}

3. Camera Example

Tạo mới một project có tên AndroidCameraDemo:

  • File > New > New Project > Empty Activity
    • Name: AndroidCameraDemo
    • Package name: org.o7planning.androidcamerademo
    • Language: Java

Thêm cấu hình cho phép đọc và ghi dữ liệu trên thiết bị.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.o7planning.androidcamerademo">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Thiết kế giao diện ví dụ:

Hướng dẫn code mở camera trên android

Nếu bạn quan tâm tới các bước để thiết kế giao diện ứng dụng này hãy xem phần phụ lục phía cuối bài viết.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="175dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="21dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_foreground"
        tools:ignore="VectorDrawableCompat" />
    <VideoView
        android:id="@+id/videoView"
        android:layout_width="0dp"
        android:layout_height="175dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/videoView">
        <Button
            android:id="@+id/button_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="Capture Image" />
        <Button
            android:id="@+id/button_video"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="Capture Video" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package org.o7planning.androidcamerademo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.os.Bundle;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
    private Button buttonImage;
    private Button buttonVideo;
    private VideoView videoView;
    private ImageView imageView;
    private static final int REQUEST_ID_READ_WRITE_PERMISSION = 99;
    private static final int REQUEST_ID_IMAGE_CAPTURE = 100;
    private static final int REQUEST_ID_VIDEO_CAPTURE = 101;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.buttonImage = (Button) this.findViewById(R.id.button_image);
        this.buttonVideo = (Button) this.findViewById(R.id.button_video);
        this.videoView = (VideoView) this.findViewById(R.id.videoView);
        this.imageView = (ImageView) this.findViewById(R.id.imageView);
        this.buttonImage.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureImage();
            }
        });
        this.buttonVideo.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                askPermissionAndCaptureVideo();
            }
        });
    }
    private void captureImage() {
        // Create an implicit intent, for image capture.
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Start camera and wait for the results.
        this.startActivityForResult(intent, REQUEST_ID_IMAGE_CAPTURE);
    }
    private void askPermissionAndCaptureVideo() {
        // With Android Level >= 23, you have to ask the user
        // for permission to read/write data on the device.
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // Check if we have read/write permission
            int readPermission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (writePermission != PackageManager.PERMISSION_GRANTED ||
                    readPermission != PackageManager.PERMISSION_GRANTED) {
                // If don't have permission so prompt the user.
                this.requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_ID_READ_WRITE_PERMISSION
                );
                return;
            }
        }
        this.captureVideo();
    }
    private void captureVideo() {
        try {
            // Create an implicit intent, for video capture.
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            // The external storage directory.
            File dir = Environment.getExternalStorageDirectory();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // file:///storage/emulated/0/myvideo.mp4
            String savePath = dir.getAbsolutePath() + "/myvideo.mp4";
            File videoFile = new File(savePath);
            Uri videoUri = Uri.fromFile(videoFile);
            // Specify where to save video files.
            intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // ================================================================================================
            // To Fix Error (**)
            // ================================================================================================
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            // ================================================================================================
            // You may get an Error (**) If your app targets API 24+
            // "android.os.FileUriExposedException: file:///storage/emulated/0/xxx exposed beyond app through.."
            //  Explanation: https://stackoverflow.com/questions/38200282
            // ================================================================================================
            // Start camera and wait for the results.
            this.startActivityForResult(intent, REQUEST_ID_VIDEO_CAPTURE); // (**)
        } catch(Exception e)  {
            Toast.makeText(this, "Error capture video: " +e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
    // When you have the request results
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //
        switch (requestCode) {
            case REQUEST_ID_READ_WRITE_PERMISSION: {
                // Note: If request is cancelled, the result arrays are empty.
                // Permissions granted (read/write).
                if (grantResults.length > 1
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission granted!", Toast.LENGTH_LONG).show();
                    this.captureVideo();
                }
                // Cancelled or denied.
                else {
                    Toast.makeText(this, "Permission denied!", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }
    // When results returned
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ID_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                Bitmap bp = (Bitmap) data.getExtras().get("data");
                this.imageView.setImageBitmap(bp);
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Action canceled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Action Failed", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_ID_VIDEO_CAPTURE) {
            if (resultCode == RESULT_OK) {
                Uri videoUri = data.getData();
                Log.i("MyLog", "Video saved to: " + videoUri);
                Toast.makeText(this, "Video saved to:\n" +
                        videoUri, Toast.LENGTH_LONG).show();
                this.videoView.setVideoURI(videoUri);
                this.videoView.start();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Action Cancelled.",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Action Failed",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}

Ứng dụng sẽ lưu video xuống SD Card của thiết bị giả lập (Emulator), vì vậy hãy đảm bảo rằng bạn đã thiết lập SD Card.

OK, bây giờ bạn có thể chạy ứng dụng. Ở đây tôi chạy ứng dụng trên thiết bị mô phỏng với Camera cũng là camera mô phỏng.