自己编写Android手电筒,支持5.0
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) { } });这几个步骤缺一不可。照网上之前的例子试了,一直不成功。就是因为有些缺了打开预览,有些缺了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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。