线程中断的替代方案?

阿努拉格·乔希(Anurag Joshi)

使用SOS模式构建Flashlight应用程序。有3个按钮(打开,关闭和SOS)。应用程序可以在正常的打开和关闭模式下运行,但不能在SOS模式下运行。(SOS模式不会关闭)

//this method gets called when Off button is pressed
    private void turnOffFlash() {
            if (FlashOn) {
                if (myCamera == null || myParameters == null) {
                    return;
                }
                myParameters = myCamera.getParameters();
                myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                myCamera.setParameters(myParameters);
                myCamera.stopPreview();
                try {
                    if (SOSon)
                        Flashthread.interrupt();
                    SOSon = false;
                } catch (Exception ex) {
                    throw ex;
                }
                FlashOn = false;
                number_of_press=0;
            }
        }

Flashthread用于这里

void onSOSPress() {
        if (number_of_press == 1) {
            try {
                SOSon = true;
                if (!Flashthread.isInterrupted()) {
                    if (SOSon) {
                        Flashthread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < System.currentTimeMillis(); i++) {
                                    if (FlashOn) {
                                        myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                                        myCamera.setParameters(myParameters);
                                        FlashOn = false;
                                    } else {
                                        TurnOnFlash();
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }
                        });
                        Flashthread.start();
                    }
                } else
                    Flashthread.resume();
            } catch (Exception ex) {
                throw ex;
            }
        }
    }

在该turnOffFlash方法中,因为我读到Interrupt方法并没有真正“中断” /杀死线程,我可以使用什么代替Thread.Interrupt();按一下Off按钮来停止SOS模式?我尝试了stop()destroy()但都使该应用程序崩溃了。

克里斯·汤普森

您应该使用Handler注释中建议的a ,但是如果您要坚持使用该系统,请使用一个标志告诉您的线程停止:

boolean shouldStop = false;

...
while (!shouldStop){
  if(FlashOn){
    ...//do SOS stuff
  }
}

...
public void endSOS(){
  shouldStop = true;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章