程序员人生 网站导航

自己编写Android手电筒,支持5.0

栏目:综合技术时间:2015-06-05 09:35:01

  android手电筒原理很简单,就是打开相机的闪光灯。

  核心的代码就这么多:

    打开相机

    设置闪光灯开

    打开预览

    设置相机的autoFocus

    Camera camera = Camera.open();     Parameters mParameters = camera.getParameters();     mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);     camera.setParameters(mParameters);     camera.startPreview();     camera.autoFocus(new AutoFocusCallback() { public void onAutoFocus(boolean success, Camera camera) { }     });
  这几个步骤缺1不可。照网上之前的例子试了,1直不成功。就是由于有些缺了打开预览,有些缺了autoFocus


  然后就是设置权限

 

    <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.FLASHLIGHT" />     <uses-feature android:name="android.hardware.camera" />     <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-feature android:name="android.hardware.camera.flash" />

  最后贴以下完全的Activity。我这个很简单,create的时候就打开手电筒,屏幕上显示”Flashlight open“,按返回键,关闭并退出利用。

   

package org.lhc.flashlight; import android.app.Activity; import android.hardware.Camera; import android.hardware.Camera.AutoFocusCallback; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.widget.TextView; public class MainActivity extends Activity { private Camera camera = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.camera = Camera.open(); if (this.camera != null) { Parameters mParameters = camera.getParameters(); mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(mParameters); camera.startPreview(); camera.autoFocus(new AutoFocusCallback() { public void onAutoFocus(boolean success, Camera camera) { } }); TextView info = (TextView)this.findViewById(R.id.flashlight_info); info.setText("Flashlight open"); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (this.camera != null) { Parameters mParameters = camera.getParameters(); mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(mParameters); camera.stopPreview(); camera.release(); } Log.i("Flashlight", "exit"); this.finish(); System.exit(0); } return super.onKeyDown(keyCode, event); } }

转载请注明出处

http://blog.csdn.net/redstarofsleep

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐