How to turn on front flash light programmatically in Android?

后端 未结 11 1745
执笔经年
执笔经年 2020-11-22 00:17

I want to turn on front flash light (not with camera preview) programmatically in Android. I googled for it but the help i found referred me to this page

Does anyo

11条回答
  •  梦如初夏
    2020-11-22 01:02

    From my experience, if your application is designed to work in both portrait and landscape orientation, you need to declare the variable cam as static. Otherwise, onDestroy(), which is called on switching orientation, destroys it but doesn't release Camera so it's not possible to reopen it again.

    package com.example.flashlight;
    
    import android.hardware.Camera;
    import android.hardware.Camera.Parameters;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.pm.PackageManager;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    public static Camera cam = null;// has to be static, otherwise onDestroy() destroys it
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void flashLightOn(View view) {
    
        try {
            if (getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_CAMERA_FLASH)) {
                cam = Camera.open();
                Parameters p = cam.getParameters();
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                cam.setParameters(p);
                cam.startPreview();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Exception flashLightOn()",
                    Toast.LENGTH_SHORT).show();
        }
    }
    
    public void flashLightOff(View view) {
        try {
            if (getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_CAMERA_FLASH)) {
                cam.stopPreview();
                cam.release();
                cam = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Exception flashLightOff",
                    Toast.LENGTH_SHORT).show();
        }
    }
    }
    

    to manifest I had to put this line

        
    

    from http://developer.android.com/reference/android/hardware/Camera.html

    suggested lines above wasn't working for me.

提交回复
热议问题