Android studio APK切换多个摄像头(Camera2)

1.先设置camera的权限

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

2.布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextureViewandroid:id="@+id/textureView"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"/><Buttonandroid:id="@+id/btnSwitchCamera"android:layout_width="match_parent"android:layout_height="100dp"android:textSize="50dp"android:text="切换相机"/></LinearLayout>

3.主界面代码

package com.example.multiplecamerasimport android.Manifest
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.view.View
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.hjq.permissions.OnPermission
import com.hjq.permissions.XXPermissionsclass MainActivity : AppCompatActivity() {private val TAG = MainActivity::class.java.simpleNameprivate var cameraManager: CameraManager? = nullprivate var cameraIds: Array<String>?=nullprivate var currentCameraIdIndex = 0private var cameraDevice: CameraDevice? = nullprivate var textureView: TextureView? = nullprivate var captureRequestBuilder: CaptureRequest.Builder? = nullprivate var cameraCaptureSession: CameraCaptureSession? = nullprivate var surfaceTexture: SurfaceTexture? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)XXPermissions.with(this).request(object : OnPermission {@RequiresApi(Build.VERSION_CODES.LOLLIPOP)override fun hasPermission(granted: List<String>, isAll: Boolean) {Log.e("TAG", "hasPermission=" + granted.size + "       " + isAll)initView()}override fun noPermission(denied: List<String>, quick: Boolean) {Log.e("TAG", "noPermission=" + denied.size + "       " + quick)}})}@RequiresApi(Build.VERSION_CODES.LOLLIPOP)fun initView(){cameraManager = getSystemService(CAMERA_SERVICE) as CameraManagertextureView = findViewById(R.id.textureView)// 设置 TextureView 的监听器,用于在 SurfaceTexture 准备好时打开相机textureView!!.surfaceTextureListener = surfaceTextureListener// 相机切换按钮的点击事件监听器findViewById<View>(R.id.btnSwitchCamera).setOnClickListener {Log.e("TAG", "switchCamera()=========")switchCamera()}}private val surfaceTextureListener: SurfaceTextureListener = object : SurfaceTextureListener {override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {surfaceTexture = surfaceLog.e("TAG", "onSurfaceTextureAvailable")openCamera()}override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture,width: Int,height: Int) {}override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {return false}override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}}@RequiresApi(Build.VERSION_CODES.LOLLIPOP)private fun openCamera() {Log.e("TAG", "openCamera============")try {cameraIds = cameraManager!!.cameraIdList} catch (e: Exception) {e.printStackTrace()}if (cameraIds != null && cameraIds!!.isNotEmpty()) {val cameraId = cameraIds!![currentCameraIdIndex]if (ActivityCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling//    ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding//   public void onRequestPermissionsResult(int requestCode, String[] permissions,//                                          int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return}Log.e("TAG", "openCamera============$cameraId")cameraManager!!.openCamera(cameraId, cameraCallback, null)}}private val cameraCallback: CameraDevice.StateCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP)object : CameraDevice.StateCallback() {@RequiresApi(Build.VERSION_CODES.O)override fun onOpened(@NonNull camera: CameraDevice) {cameraDevice = cameraLog.e("TAG", "onOpened============$cameraDevice")startPreview()}override fun onDisconnected(@NonNull camera: CameraDevice) {cameraDevice!!.close()}override fun onError(@NonNull camera: CameraDevice, error: Int) {cameraDevice!!.close()}}@RequiresApi(Build.VERSION_CODES.O)private fun startPreview() {if (cameraDevice == null) {return}Log.e("TAG", "startPreview=====1=======$cameraDevice")try {val surface = Surface(surfaceTexture)// 创建 CaptureRequest.Builder,并设置 Surface 作为目标captureRequestBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)captureRequestBuilder!!.addTarget(surface)Log.e("TAG", "startPreview===2=========${cameraDevice!!.id}")// 创建相机捕获会话cameraDevice!!.createCaptureSession(listOf(surface),captureSessionCallback,null)} catch (e: Exception) {Log.e("TAG", "e============${e.message}")}}private val captureSessionCallback: CameraCaptureSession.StateCallback =@RequiresApi(Build.VERSION_CODES.LOLLIPOP)object : CameraCaptureSession.StateCallback() {override fun onConfigured(@NonNull session: CameraCaptureSession) {cameraCaptureSession = session// 设置重复预览请求try {cameraCaptureSession!!.setRepeatingRequest(captureRequestBuilder!!.build(),null,null)} catch (e: CameraAccessException) {e.printStackTrace()}}override fun onConfigureFailed(@NonNull session: CameraCaptureSession) {Log.e(TAG, "Failed to configure camera capture session")}}private fun switchCamera() {if (cameraIds != null && cameraIds!!.size > 1) {cameraDevice!!.close()currentCameraIdIndex = (currentCameraIdIndex + 1) % cameraIds!!.sizeval cameraId = cameraIds!![currentCameraIdIndex]try {if (ActivityCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling//    ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding//   public void onRequestPermissionsResult(int requestCode, String[] permissions,//                                          int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return}cameraManager!!.openCamera(cameraId, cameraCallback, null)} catch (e: CameraAccessException) {e.printStackTrace()}}}@RequiresApi(Build.VERSION_CODES.LOLLIPOP)override fun onPause() {super.onPause()cameraDevice?.close()}override fun onResume() {super.onResume()if (cameraDevice == null && surfaceTexture != null) {openCamera()}}}

XXPermissions.with(this).request(object : OnPermission {@RequiresApi(Build.VERSION_CODES.LOLLIPOP)override fun hasPermission(granted: List<String>, isAll: Boolean) {Log.e("TAG", "hasPermission=" + granted.size + "       " + isAll)}override fun noPermission(denied: List<String>, quick: Boolean) {Log.e("TAG", "noPermission=" + denied.size + "       " + quick)}})

这部分代码是用来授权AndroidManifest.xml里面权限的第三方sdk代码

效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/87637.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

服务器部署前后端项目-SQL Father为例

hello~大家好哇&#xff0c;好久没更新博客了。现在来更新一波hhh 现在更新一下部署上的一些东西&#xff0c;因为其实有很多小伙伴跟我之前一样&#xff0c;很多时候只是开发了&#xff0c;本地前后端都能调通&#xff0c;也能用&#xff0c;但是没有部署到服务器试过&#x…

新SDK平台下载开源全志V853的SDK

获取SDK SDK 使用 Repo 工具管理&#xff0c;拉取 SDK 需要配置安装 Repo 工具。 Repo is a tool built on top of Git. Repo helps manage many Git repositories, does the uploads to revision control systems, and automates parts of the development workflow. Repo is…

用NeRFMeshing精确提取NeRF网络中的3D网格

准确的 3D 场景和对象重建对于机器人、摄影测量和 AR/VR 等各种应用至关重要。 NeRF 在合成新颖视图方面取得了成功&#xff0c;但在准确表示底层几何方面存在不足。 推荐&#xff1a;用 NSDT编辑器 快速搭建可编程3D场景 我们已经看到了最新的进展&#xff0c;例如 NVIDIA 的…

【算法与数据结构】404、LeetCode左叶子之和

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;思路比较简单&#xff0c;遍历所有节点然后判断该节点是否为左叶子节点&#xff0c;如果是&#xff0c…

文件夹无法删除?简单3招,轻松解决问题!

“我电脑里有一个文件夹占用了很大的内存&#xff0c;我想将它删除来释放一些内存&#xff0c;但是根本没法删除&#xff0c;为什么会这样呢&#xff1f;文件夹无法删除应该怎么办呢&#xff1f;” 在日常电脑使用中&#xff0c;有时候会遇到文件夹无法删除的情况&#xff0c;这…

“互联网+”背景下燃气行业的数字化之路

文章来源&#xff1a;智慧美好生活 关键词&#xff1a;智慧燃气、智慧燃气场站、智慧燃气平台、设备设施数字化、数字孪生、工业互联网 近年来&#xff0c;随着互联网行业的发展&#xff0c;其影响力正在逐渐渗透到各个领域。在能源行业&#xff0c;各个互联网巨头与燃气企业…

STM32 CubeMX (H750)RGB屏幕 LTDC

STM32 CubeMX STM32 RGB888 LTDC STM32 CubeMX一、STM32 CubeMX 设置时钟树LTDC使能设置屏幕参数修改RGB888的GPIO 二、代码部分效果 RGB屏幕线束定义&#xff1a; 一、STM32 CubeMX 设置 时钟树 这里设置的时钟&#xff0c;关于刷新速度 举例子&#xff1a;LCD_CLK24MHz 时…

网易新财报:游戏稳、有道进、云音乐正爬坡

今年以来&#xff0c;AI大模型的火热程度屡屡攀升&#xff0c;越来越多的企业都加入到了AI大模型的赛场中&#xff0c;纷纷下场布局。而在众多参与者中&#xff0c;互联网企业的身影更是频频浮现&#xff0c;比如&#xff0c;百度、阿里巴巴、腾讯等等。值得一提的是&#xff0…

自然语言处理(三):基于跳元模型的word2vec实现

跳元模型 回顾一下第一节讲过的跳元模型 跳元模型&#xff08;Skip-gram Model&#xff09;是一种用于学习词向量的模型&#xff0c;属于Word2Vec算法中的一种。它的目标是通过给定一个中心词语来预测其周围的上下文词语。 这节我们以跳元模型为例&#xff0c;讲解word2vec的…

改进YOLO系列:6.添加ECA注意力机制

添加ECA注意力机制 1. ECA注意力机制论文2. ECA注意力机制原理3. ECA注意力机制的配置3.1common.py配置3.2yolo.py配置3.3yaml文件配置1. ECA注意力机制论文 论文题目:ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks 论文链接:ECA-N…

树模型与集成学习:LightGBM

目录 树模型与集成学习 LightGBM 的贡献 LightGBM 的贡献&#xff1a;单边梯度抽样算法 LightGBM 的贡献&#xff1a;直方图算法 LightGBM 的贡献&#xff1a;互斥特征捆绑算法 LightGBM 的贡献&#xff1a;深度限制的 Leaf-wise 算法 树模型与集成学习 树模型是非常好的…

基于SpringBoot的员工(人事)管理系统

基于SpringBoot的员工&#xff08;人事&#xff09;管理系统 一、系统介绍二、功能展示三.其他系统实现五.获取源码 一、系统介绍 项目名称&#xff1a;基于SPringBoot的员工管理系统 项目架构&#xff1a;B/S架构 开发语言&#xff1a;Java语言 前端技术&#xff1a;BootS…