1.AndroidManifest.xml 加入
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
2.main.xml
2.MainActivity.java
package com.prgguru.com; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private boolean isFlashOn = false; //預設開關-關閉 private Camera camera; private Button button; @Override protected void onStop() { super.onStop(); if (camera != null) { camera.release(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button) findViewById(R.id.buttonFlashlight); Context context = this; PackageManager pm = context.getPackageManager(); if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { //判斷有無相機 Toast.makeText(getApplicationContext(), "抱歉,您的手機無相機功能", Toast.LENGTH_SHORT).show(); return; } camera = Camera.open(); final Parameters p = camera.getParameters(); button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { if (isFlashOn) { //false 關閉 p.setFlashMode(Parameters.FLASH_MODE_OFF); //相機閃光燈模式 camera.setParameters(p); isFlashOn = false; button.setText("打開"); } else { // true 開啟 Log.i("info", "torch is turned on!"); p.setFlashMode(Parameters.FLASH_MODE_TORCH); //相機閃光燈模式 camera.setParameters(p); isFlashOn = true; button.setText("關閉"); } } }); } }參考來源: http://programmerguru.com/android-tutorial/android-flashlight-example/
沒有留言 :
張貼留言