当前位置:   article > 正文

Android studio APK切换多个摄像头(Camera2)_android 如何切换camera

android 如何切换camera

1.先设置camera的权限

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

2.布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextureView
  7. android:id="@+id/textureView"
  8. android:layout_width="match_parent"
  9. android:layout_height="0dp"
  10. android:layout_weight="1"/>
  11. <Button
  12. android:id="@+id/btnSwitchCamera"
  13. android:layout_width="match_parent"
  14. android:layout_height="100dp"
  15. android:textSize="50dp"
  16. android:text="切换相机"/>
  17. </LinearLayout>

3.主界面代码

  1. package com.example.multiplecameras
  2. import android.Manifest
  3. import android.content.pm.PackageManager
  4. import android.graphics.SurfaceTexture
  5. import android.hardware.camera2.*
  6. import android.os.Build
  7. import android.os.Bundle
  8. import android.util.Log
  9. import android.view.Surface
  10. import android.view.TextureView
  11. import android.view.TextureView.SurfaceTextureListener
  12. import android.view.View
  13. import androidx.annotation.NonNull
  14. import androidx.annotation.RequiresApi
  15. import androidx.appcompat.app.AppCompatActivity
  16. import androidx.core.app.ActivityCompat
  17. import com.hjq.permissions.OnPermission
  18. import com.hjq.permissions.XXPermissions
  19. class MainActivity : AppCompatActivity() {
  20. private val TAG = MainActivity::class.java.simpleName
  21. private var cameraManager: CameraManager? = null
  22. private var cameraIds: Array<String>?=null
  23. private var currentCameraIdIndex = 0
  24. private var cameraDevice: CameraDevice? = null
  25. private var textureView: TextureView? = null
  26. private var captureRequestBuilder: CaptureRequest.Builder? = null
  27. private var cameraCaptureSession: CameraCaptureSession? = null
  28. private var surfaceTexture: SurfaceTexture? = null
  29. override fun onCreate(savedInstanceState: Bundle?) {
  30. super.onCreate(savedInstanceState)
  31. setContentView(R.layout.activity_main)
  32. XXPermissions.with(this)
  33. .request(object : OnPermission {
  34. @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  35. override fun hasPermission(granted: List<String>, isAll: Boolean) {
  36. Log.e("TAG", "hasPermission=" + granted.size + " " + isAll)
  37. initView()
  38. }
  39. override fun noPermission(denied: List<String>, quick: Boolean) {
  40. Log.e("TAG", "noPermission=" + denied.size + " " + quick)
  41. }
  42. })
  43. }
  44. @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  45. fun initView(){
  46. cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
  47. textureView = findViewById(R.id.textureView)
  48. // 设置 TextureView 的监听器,用于在 SurfaceTexture 准备好时打开相机
  49. textureView!!.surfaceTextureListener = surfaceTextureListener
  50. // 相机切换按钮的点击事件监听器
  51. findViewById<View>(R.id.btnSwitchCamera).setOnClickListener {
  52. Log.e("TAG", "switchCamera()=========")
  53. switchCamera()
  54. }
  55. }
  56. private val surfaceTextureListener: SurfaceTextureListener = object : SurfaceTextureListener {
  57. override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
  58. surfaceTexture = surface
  59. Log.e("TAG", "onSurfaceTextureAvailable")
  60. openCamera()
  61. }
  62. override fun onSurfaceTextureSizeChanged(
  63. surface: SurfaceTexture,
  64. width: Int,
  65. height: Int
  66. ) {
  67. }
  68. override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
  69. return false
  70. }
  71. override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
  72. }
  73. @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  74. private fun openCamera() {
  75. Log.e("TAG", "openCamera============")
  76. try {
  77. cameraIds = cameraManager!!.cameraIdList
  78. } catch (e: Exception) {
  79. e.printStackTrace()
  80. }
  81. if (cameraIds != null && cameraIds!!.isNotEmpty()) {
  82. val cameraId = cameraIds!![currentCameraIdIndex]
  83. if (ActivityCompat.checkSelfPermission(
  84. this,
  85. Manifest.permission.CAMERA
  86. ) != PackageManager.PERMISSION_GRANTED
  87. ) {
  88. // TODO: Consider calling
  89. // ActivityCompat#requestPermissions
  90. // here to request the missing permissions, and then overriding
  91. // public void onRequestPermissionsResult(int requestCode, String[] permissions,
  92. // int[] grantResults)
  93. // to handle the case where the user grants the permission. See the documentation
  94. // for ActivityCompat#requestPermissions for more details.
  95. return
  96. }
  97. Log.e("TAG", "openCamera============$cameraId")
  98. cameraManager!!.openCamera(cameraId, cameraCallback, null)
  99. }
  100. }
  101. private val cameraCallback: CameraDevice.StateCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  102. object : CameraDevice.StateCallback() {
  103. @RequiresApi(Build.VERSION_CODES.O)
  104. override fun onOpened(@NonNull camera: CameraDevice) {
  105. cameraDevice = camera
  106. Log.e("TAG", "onOpened============$cameraDevice")
  107. startPreview()
  108. }
  109. override fun onDisconnected(@NonNull camera: CameraDevice) {
  110. cameraDevice!!.close()
  111. }
  112. override fun onError(@NonNull camera: CameraDevice, error: Int) {
  113. cameraDevice!!.close()
  114. }
  115. }
  116. @RequiresApi(Build.VERSION_CODES.O)
  117. private fun startPreview() {
  118. if (cameraDevice == null) {
  119. return
  120. }
  121. Log.e("TAG", "startPreview=====1=======$cameraDevice")
  122. try {
  123. val surface = Surface(surfaceTexture)
  124. // 创建 CaptureRequest.Builder,并设置 Surface 作为目标
  125. captureRequestBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
  126. captureRequestBuilder!!.addTarget(surface)
  127. Log.e("TAG", "startPreview===2=========${cameraDevice!!.id}")
  128. // 创建相机捕获会话
  129. cameraDevice!!.createCaptureSession(
  130. listOf(surface),
  131. captureSessionCallback,
  132. null
  133. )
  134. } catch (e: Exception) {
  135. Log.e("TAG", "e============${e.message}")
  136. }
  137. }
  138. private val captureSessionCallback: CameraCaptureSession.StateCallback =
  139. @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  140. object : CameraCaptureSession.StateCallback() {
  141. override fun onConfigured(@NonNull session: CameraCaptureSession) {
  142. cameraCaptureSession = session
  143. // 设置重复预览请求
  144. try {
  145. cameraCaptureSession!!.setRepeatingRequest(
  146. captureRequestBuilder!!.build(),
  147. null,
  148. null
  149. )
  150. } catch (e: CameraAccessException) {
  151. e.printStackTrace()
  152. }
  153. }
  154. override fun onConfigureFailed(@NonNull session: CameraCaptureSession) {
  155. Log.e(TAG, "Failed to configure camera capture session")
  156. }
  157. }
  158. private fun switchCamera() {
  159. if (cameraIds != null && cameraIds!!.size > 1) {
  160. cameraDevice!!.close()
  161. currentCameraIdIndex = (currentCameraIdIndex + 1) % cameraIds!!.size
  162. val cameraId = cameraIds!![currentCameraIdIndex]
  163. try {
  164. if (ActivityCompat.checkSelfPermission(
  165. this,
  166. Manifest.permission.CAMERA
  167. ) != PackageManager.PERMISSION_GRANTED
  168. ) {
  169. // TODO: Consider calling
  170. // ActivityCompat#requestPermissions
  171. // here to request the missing permissions, and then overriding
  172. // public void onRequestPermissionsResult(int requestCode, String[] permissions,
  173. // int[] grantResults)
  174. // to handle the case where the user grants the permission. See the documentation
  175. // for ActivityCompat#requestPermissions for more details.
  176. return
  177. }
  178. cameraManager!!.openCamera(cameraId, cameraCallback, null)
  179. } catch (e: CameraAccessException) {
  180. e.printStackTrace()
  181. }
  182. }
  183. }
  184. @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  185. override fun onPause() {
  186. super.onPause()
  187. cameraDevice?.close()
  188. }
  189. override fun onResume() {
  190. super.onResume()
  191. if (cameraDevice == null && surfaceTexture != null) {
  192. openCamera()
  193. }
  194. }
  195. }

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代码

效果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/182026
推荐阅读
相关标签
  

闽ICP备14008679号