收到来电时闪烁手电筒

时间:2015-01-13 12:24:29

标签: android broadcastreceiver

我正在尝试做一个应用程序,当收到来电时,移动LED手电筒会闪烁。

BroadcastReceiver代码:

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;

        }
    }
}

这就是我试图这样做的方式。它在第一次通话时工作正常。当我进行第二次呼叫时,指示灯不闪烁,但正确地获取吐司信息。我在这做错了什么?

1 个答案:

答案 0 :(得分:0)

同样简单,请致电:

    camera.release();

    camera.stopPreview();