開啟android設備的閃光燈作為手電筒

手電筒是使用Android手機的閃光燈,所以需添加權限

我測試的手機是三星I9300,正常,界面沒有美化就有一個按鈕,代碼如下:

package com.jwzhangjie;

import com.jwzhangjie.test.R;

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;

/**
 * 手電筒
 * @author jwzhangjie
 *
 */
public class CameraLight extends Activity{

	private Button openLight;
	private boolean status = false;
	private Camera camera;
	private Parameters parameters;
	private CameraLight instance;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cameralight);
		instance = this;
		camera = Camera.open();
		openLight = (Button)findViewById(R.id.openLight);
		openLight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!status) {
					openLight.setText("關閉");
					status = true;
					new Thread(new TurnOnLight()).start();
				}else {
					status = false;
					openLight.setText("打開");
					instance.parameters.setFlashMode("off");
					instance.camera.setParameters(instance.parameters);
				}
			}
		});
		
	}
	
	
	private class TurnOnLight implements Runnable{
		@Override
		public void run() {
			instance.parameters = instance.camera.getParameters();
			instance.parameters.setFlashMode("torch");
			instance.camera.setParameters(instance.parameters);
		}
	}
 }



發佈留言