package com.example.flashlight
import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var flashLightStatus: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
openFlashLight()
while (true) {
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
openFlashLight()
}, 5000)
}
}
private fun openFlashLight() {
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraId = cameraManager.cameraIdList[0]
if (!flashLightStatus) {
try {
cameraManager.setTorchMode(cameraId, true)
flashLightStatus = true
} catch (e: CameraAccessException) {
}
} else {
try {
cameraManager.setTorchMode(cameraId, false)
flashLightStatus = false
} catch (e: CameraAccessException) {
}
}
}
private fun closeFlashLight()
{
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraId = cameraManager.cameraIdList[0]
if (flashLightStatus) {
try {
cameraManager.setTorchMode(cameraId, false)
flashLightStatus = false
} catch (e: CameraAccessException) {
}
} else {
try {
cameraManager.setTorchMode(cameraId, true)
flashLightStatus = true
} catch (e: CameraAccessException) {
}
}
}
}
这现在只需要打开手机上的手电筒,手电筒一直保持打开状态,因为while(true)
while (true) {
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
openFlashLight()
}, 5000)
}
但如果我移除while true并只执行:
openFlashLight()
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
这将打开手电筒,并将等待5秒钟,然后将关闭手电筒。但是我想做一些无穷无尽的东西,它会打开闪光灯,等待5秒,关闭闪光灯,等待5秒,打开闪光灯,等待5秒,关闭。
一直往那边走。每5秒开启/关闭一次,不间断。这就是为什么我试图使用while(true)
,但手电筒只是保持开放不停。
2条答案
按热度按时间rsl1atfo1#
如果你想每5秒重复一次手电筒的开/关周期,你可以这样做:
1.将boolean标志作为类成员:
1.做一个启动手电筒的方法
1.要停止此处理程序调用,请执行以下操作:
handler.removeCallbacksAndMessages(null)
56lgkhnf2#
您可以通过使用Kotlin协程来实现这一点
并在build.gradle模块级别文件中添加此依赖项
如果你想用handler来做,你可以试试这个,我不确定这是否有效。