码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-04-30 10:42:44      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:android   camera   手电筒   闪光灯   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

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

标签:android   camera   手电筒   闪光灯   5.0   

原文地址:http://blog.csdn.net/redstarofsleep/article/details/45390683

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!