gpt4 book ai didi

android - 无法使闪光灯连续闪烁并在单击按钮时停止

转载 作者:行者123 更新时间:2023-11-30 04:54:29 29 4
gpt4 key购买 nike

我试图让手电筒在连续按下按钮时闪烁,直到再次按下按钮。闪光灯持续闪烁,但我无法停止闪烁,因为应用程序卡住了。这是我的代码:

public void Buts1(View view) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
long blinkDelay = 50;//delay in ms
if(textView.getText().toString().equals("ON")){
boolean s=false;
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

最佳答案

我相信您在这里卡住了 UI 线程。此外,我没有看到任何将 textView 文本设置为“OFF”的内容。

我稍微修改了您的代码,假定 textView 以文本“OFF”开头,并在您单击按钮时更改为“ON”。再次单击该按钮会将 textView 文本设置为“OFF”并关闭闪烁。这是通过在单独的线程而不是 UI 线程上工作的。

        button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Thread flashThread = new Thread(new Runnable() {
@Override
public void run() {
boolean s=false;
long blinkDelay = 50;//delay in ms
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}
});
if(textView.getText().toString().equalsIgnoreCase("OFF")){
textView.setText("ON");
flashThread.start();
}else{
flashThread.interrupt();
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
textView.setText("OFF");
}
}
});

关于android - 无法使闪光灯连续闪烁并在单击按钮时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59471258/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com