在线程中释放相机
Releasing the camera within a thread
我正在创建一个简单的摩尔斯电码应用程序。用户可以输入文本,然后将其翻译成莫尔斯码并在新线程中按顺序闪烁。我已经实现了一个 for 循环,用于转动 on/off 相机闪光灯来表示莫尔斯序列。
问题是,当用户离开 activity 时,暂停方法会释放相机,但我有时会收到错误 'method called after release'。我不确定如何在释放相机时取消来自 运行 的线程。我已经尝试使用一个 volatile 布尔值,该值在每次循环迭代开始时进行检查,但是如果在除开始之外的任何其他时间取消循环,则会导致错误。
有没有人ideas/suggestions知道我该如何解决这个问题?
public void flashTranslation(String message) {
int offIntervalTime = 50;
char[] cArray = message.toCharArray();
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == '.') {
turnOn();
try {
Thread.sleep(50);
}catch(Exception e)
{
Log.d("One", "Two");
}
turnOff();
try {
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
} else if(cArray[i] == ' ')
{
Log.d("EMPTY!", "EMPTY!");
try{
Thread.sleep(100);
}catch(Exception e)
{
}
}
else {
try{
turnOn();
Thread.sleep(dash);
}catch(Exception e)
{
}
try{
turnOff();
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
}
}
}
最简单的方法是取消通过信号量防止并发访问的线程。每次尝试在线程上闪烁时,都会检查线程是否被取消。伪代码:
Semaphore sem;
onPause(){
sem.take();
camera.turnOff();
camera.release();
thread.cancel();
sem.give();
}
thread.run() {
//This should be run before every call to turnOn or turnoff
sem.take();
if(isCanceled()) {
return;
}
turnOn();
sem.give();
}
onResume() {
new Thread.start();
}
我正在创建一个简单的摩尔斯电码应用程序。用户可以输入文本,然后将其翻译成莫尔斯码并在新线程中按顺序闪烁。我已经实现了一个 for 循环,用于转动 on/off 相机闪光灯来表示莫尔斯序列。
问题是,当用户离开 activity 时,暂停方法会释放相机,但我有时会收到错误 'method called after release'。我不确定如何在释放相机时取消来自 运行 的线程。我已经尝试使用一个 volatile 布尔值,该值在每次循环迭代开始时进行检查,但是如果在除开始之外的任何其他时间取消循环,则会导致错误。
有没有人ideas/suggestions知道我该如何解决这个问题?
public void flashTranslation(String message) {
int offIntervalTime = 50;
char[] cArray = message.toCharArray();
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == '.') {
turnOn();
try {
Thread.sleep(50);
}catch(Exception e)
{
Log.d("One", "Two");
}
turnOff();
try {
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
} else if(cArray[i] == ' ')
{
Log.d("EMPTY!", "EMPTY!");
try{
Thread.sleep(100);
}catch(Exception e)
{
}
}
else {
try{
turnOn();
Thread.sleep(dash);
}catch(Exception e)
{
}
try{
turnOff();
Thread.sleep(offIntervalTime);
}catch(Exception e)
{
}
}
}
}
最简单的方法是取消通过信号量防止并发访问的线程。每次尝试在线程上闪烁时,都会检查线程是否被取消。伪代码:
Semaphore sem;
onPause(){
sem.take();
camera.turnOff();
camera.release();
thread.cancel();
sem.give();
}
thread.run() {
//This should be run before every call to turnOn or turnoff
sem.take();
if(isCanceled()) {
return;
}
turnOn();
sem.give();
}
onResume() {
new Thread.start();
}