3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Android] カメラのライト制御 (パーミッション不要)

Last updated at Posted at 2019-10-13

概要

APIレベル23 / Android 6.0 / Marshmallowから、従来手法では必要だった"android.permission.FLASHLIGHT"のパーミッション不要でカメラのライトのON/OFF制御が出来るようになっています。この対応方法について説明します。

コード

android.hardware.camera2.CameraManagerを利用します。サンプルコードを以下に記載しますが、とっても簡単に対応出来ます。

FlashlightTorchCOntroller
import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.camera2.CameraManager;

import androidx.annotation.NonNull;
import android.os.Handler;

@TargetApi(23)
public class FlashlightTorchController {

    private CameraManager cameraManager;
    private String cameraID;
    private boolean SW;

    public FlashlightTorchController(Context context) {

        SW = false;
        cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

        // カメラマネージャーにトーチモードのコールバックを登録
        cameraManager.registerTorchCallback(new CameraManager.TorchCallback() {
            // トーチモードが変更された時の処理
            @Override
            public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
                super.onTorchModeChanged(cameraId, enabled);
                // カメラIDをセット
                cameraID = cameraId;
                // SWに現在の状態をセット
                SW = enabled;
            }
        }, new Handler());
    }

    public void toggle() {

        if (cameraManager == null || cameraID == null)
            return ;

        cameraManager.setTorchMode(cameraID, !SW);
    }
}
3
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?