Android: how to blink LED/flashlight rapidly

后端 未结 1 870
星月不相逢
星月不相逢 2021-01-15 06:49

I am trying to show some effects with the LED/flashlight, but it is not blinking rapidly. I even tried sleep(2), but it takes time to blink. I want it to blink

相关标签:
1条回答
  • 2021-01-15 07:18

    Where do you set your preview display?

    https://developer.android.com/reference/android/hardware/Camera.html

    Important: Pass a fully initialized SurfaceHolder to setPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.

    cam.setPreviewDisplay(null);
    

    Maybe you should try this:

    Thread t = new Thread() {
        public void run() {
            try {
                // Switch on the cam for app's life
                if (mCamera == null) {
                    // Turn on Cam
                    mCamera = Camera.open();
                    try {
                        mCamera.setPreviewDisplay(null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();
                }
    
                for (int i=0; i < times*2; i++) {
                    toggleFlashLight();
                    sleep(delay);
                }
    
                if (mCamera != null) {
                    mCamera.stopPreview();
                    mCamera.release();
                    mCamera = null;
                }
            } catch (Exception e){ 
                e.printStackTrace(); 
            }
        }
    };
    
    t.start();
    

    Needed functions:

    /** Turn the devices FlashLight on */
    public void turnOn() {
        if (mCamera != null) {
        // Turn on LED
        mParams = mCamera.getParameters();
        mParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(mParams);
    
        on = true;
    }
    }
    
    /** Turn the devices FlashLight off */
    public void turnOff() {
        // Turn off flashlight
        if (mCamera != null) {
            mParams = mCamera.getParameters();
            if (mParams.getFlashMode().equals(Parameters.FLASH_MODE_TORCH)) {
                mParams.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(mParams);
            }
        }
        on = false;
    }
    
    /** Toggle the flashlight on/off status */
    public void toggleFlashLight() {
        if (!on) { // Off, turn it on
            turnOn();
        } else { // On, turn it off
            turnOff();
        }
    }
    

    and needed instance vars:

    Camera mCamera;
    Camera.Parameters mParameters;
    int delay = 100; // in ms
    
    0 讨论(0)
提交回复
热议问题