来电时闪烁手电筒

Blink flashlight when an incoming call receives

我正在尝试做一个应用程序,它可以让移动 LED 手电筒在接到来电时闪烁。

广播接收者代码:

public class IncomingCallInterceptor extends BroadcastReceiver {                                    // 1

    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Camera.Parameters params;

    @Override
    public void onReceive(Context context, Intent intent) {                                         // 2
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);                         // 3
        String msg = "Ringing" + state;

        if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {                                   // 4
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);  // 5
           // msg += ". Incoming number is " + incomingNumber;

            // TODO This would be a good place to "Do something when the phone rings" ;-)
            String myString = "0101010101";
            long blinkDelay = 50;
            getCamera();


            for (int i = 0; i < myString.length(); i++) {
                if (myString.charAt(i) == '0') {
                    // params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
                    turnOnFlash();
                } else {
                    // params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    turnOffFlash();
                }
                try {
                    Thread.sleep(blinkDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();

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



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


        }

    }

    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
            }
        }
    }
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }


            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;

        }
    }
}

这就是我尝试做到这一点的方式。第一次通话工作正常。当我拨打第二个电话时,指示灯不会闪烁,但会正确收到吐司消息。我在这里做错了什么??

就这么简单,调用:

    camera.release();

之后

    camera.stopPreview();