android利用闪光灯实现手机电筒

activity


import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private ImageView ivLight;// 闪关灯开关
	private boolean isLight_on;// 闪光灯是否开启
	private Camera camera;
	private SurfaceView cameraBG;// 相机预览
	private boolean isFirstOpenCamera;// 标记是否是第一次使用闪光

	/** Called when the activity is first created. */
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ivLight = (ImageView) this.findViewById(R.id.my_iv_light);
		cameraBG = (SurfaceView) findViewById(R.id.my_camrea);// 相机预览
		if (camera != null) {
			camera.release();// 相机释放
		}
		camera = Camera.open();// 打开相机
		ivLight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!isFirstOpenCamera) {
					Log.d("1", "**********");
					try {
						camera.setPreviewDisplay(cameraBG.getHolder());// 设置相机预览
					} catch (IOException e) {
						e.printStackTrace();
					}
					camera.startPreview();// 开始预览
					isFirstOpenCamera=true;
				}
				Camera.Parameters param = camera.getParameters();
				if (!isLight_on) {
					param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
					ivLight.setImageResource(R.drawable.light_on);
					isLight_on = true;
				} else {
					param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
					ivLight.setImageResource(R.drawable.light_off);
					isLight_on = false;
				}
				camera.setParameters(param);

			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (camera != null) {
			camera.release();// 相机释放
		}
		Log.d("2", "**********");
	}
}


xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/my_iv_light"
        android:src="@drawable/light_off"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <SurfaceView
        android:id="@+id/my_camrea"
        android:visibility="gone"
        android:layout_width="20dp"
        android:layout_height="20dp" />

</LinearLayout>

权限

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


阅读更多
文章标签: android
个人分类: 手机硬件的调用
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭