How to make android phone flashlight blink?

2020-04-19 05:03发布

I am trying to make the LED flashlight of android phone blink based on binary code like if char = 1 turn LED light on else if char = 0 turn LED off.

if ( char == '1'){ params.setFlashMode(Parameters.FLASH_MODE_ON); }              
if ( char == '0'){ params.setFlashMode(Parameters.FLASH_MODE_OFF);}

So I get the char from a String str ="101010101" the char gets the values 1, 0, 1 and so on, which is supposed to make the flashlight blink, however it blinks ones and that's it. How should I fix this problem?. Thanks

3条回答
成全新的幸福
2楼-- · 2020-04-19 05:22
String[] list1 = { "1", "0", "1", "0", "1", "0", "1", "0", "1", "0" };
        for (int i = 0; i < list1.length; i++) {
            if (list1[i].equals("0")) {
                params.setFlashMode(Parameters.FLASH_MODE_ON);
            } else {
                params.setFlashMode(Parameters.FLASH_MODE_OFF);
            }

        }

may be your problem solved but I think this one is too fast to blink......

查看更多
手持菜刀,她持情操
3楼-- · 2020-04-19 05:39

Try this :

String myString = "0101010101";
long blinkDelay = 50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
   if (myString.charAt(i) == '0') {
      params.setFlashMode(Parameters.FLASH_MODE_ON);
   } else {
      params.setFlashMode(Parameters.FLASH_MODE_OFF);
   }
   try {
      Thread.sleep(blinkDelay);
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}

Without the "Thread.sleep()" your code is probably too fast.

查看更多
可以哭但决不认输i
4楼-- · 2020-04-19 05:42

use this method it works, im using in my app

private void blink(final int delay, final int times) {
        Thread t = new Thread() {
            public void run() {
                try {

                    for (int i=0; i < times*2; i++) {
                        if (isFlashOn) {
                            turnOffFlash();
                        } else {
                            turnOnFlash();
                        }
                        sleep(delay);
                    }

                } catch (Exception e){ 
                    e.printStackTrace(); 
                }
            }
        };
        t.start();
        }

     private void turnOnFlash() {
        if (!isFlashOn) {
            if (camera == null || params == null) {
                return;
            }

            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;
        }

    }

    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;
        }
    }
查看更多
登录 后发表回答