package com.home.light; import android.app.Activity; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.home.cameralight.R; public class TestActivity extends Activity implements OnClickListener { Camera camera; Parameters params; private Button onBtn; private Button offBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); camera = Camera.open(); params = camera.getParameters(); findView(); } private void findView() { onBtn = (Button) findViewById(R.id.main_btn_on); onBtn.setOnClickListener(this); offBtn = (Button) findViewById(R.id.main_btn_off); offBtn.setOnClickListener(this); } @Override public void onClick(View v) { if (v == onBtn) { // open1(); open2(); } else if (v == offBtn) { // off1(); off2(); } } private void open1() { if (camera == null) { camera = Camera.open(); params = camera.getParameters(); } params.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(params); } private void off1() { if (camera == null) { return; } params.setFlashMode(Parameters.FLASH_MODE_OFF); camera.setParameters(params); camera.release(); camera = null; } private void open2() { if (camera == null) { camera = Camera.open(); params = camera.getParameters(); } params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(params); camera.autoFocus(new Camera.AutoFocusCallback() { public void onAutoFocus(boolean success, Camera camera) { } }); camera.startPreview(); } private void off2() { if (camera == null) { return; } camera.stopPreview(); camera.release(); camera = null; } }
权限:
<uses-permission android:name="android.permission.FLASHLIGHT" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.autofocus"/>
原文地址:http://blog.csdn.net/u010142437/article/details/40046953