按下电源按钮时如何停止维修

时间:2014-03-14 08:12:42

标签: android service keyevent

我正在制作一个应用程序,其中我想在来电时闪烁手电筒并且应用程序运行正常但问题是我想按下电源按钮时手电筒必须停止闪烁... 按下电源按钮后如何停止手电筒?

if(callState==TelephonyManager.CALL_STATE_RINGING) {
        try {

            releaseCameraAndPreview();
            cam = Camera.open();
            p = cam.getParameters();

            String myString = "010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101011";
            long blinkDelay = 50;


            for (int i = 0; i < myString.length(); i++) {
                //state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                callState = mgr.getCallState();

                /*KeyEvent event = null;
                if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    cam.release();

                }*/

public boolean onKeyDown(int keyCode, KeyEvent event)//this line is giving errors
 {
                    if (keyCode == KeyEvent.KEYCODE_POWER) {
                        p.setFlashMode(Parameters.FLASH_MODE_OFF);
                        cam.release();
                        event.startTracking(); // Needed to track long presses
                        return true;
                    }
                    return super.onKeyDown(keyCode, event);
                };

                if (callState==TelephonyManager.CALL_STATE_IDLE){
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    cam.release();
                    break;                  

                    }else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
                        p.setFlashMode(Parameters.FLASH_MODE_OFF);
                        cam.release();
                    break;  
                    }               

                if (myString.charAt(i) == '0') {
                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    cam.setParameters(p);
                } else {
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    cam.setParameters(p);
                }

                    Thread.sleep(blinkDelay);


            }
        }catch (Exception e) {
            // TODO: handle exception
            Log.d(tag, "in catch1");
            Log.d(tag, e.toString());

    }

1 个答案:

答案 0 :(得分:0)

您可以制作广播接收器以按下电源按钮 广播抓住按钮,你可以关掉手电筒。

试试这个方法。我能找到答案 How to hook into the Power button in Android?