標籤:
實現步驟1. 修改布局檔案代碼activity_main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 7 <Button 8 android:id="@+id/btn_flash" 9 android:layout_width="match_parent"10 android:layout_height="wrap_content"11 android:text="手電筒已關閉!"/>12 13 </LinearLayout>
2. 在AndroidManifest.xml中增加需要使用的許可權
1 <!-- 網路攝影機、手電筒 -->2 <uses-permission android:name="android.permission.CAMERA" />3 <uses-permission android:name="android.permission.FLASHLIGHT" />4 <uses-feature android:name="android.hardware.camera" />5 <uses-feature android:name="android.hardware.camera.autofocus" />6 <uses-feature android:name="android.hardware.camera.flash" />
- android.permission.CAMERA:Required to be able to access the camera device.
- android.permission.FLASHLIGHT:Allows access to the flashlight
3. 修改MainActivity
1 package com.example.test; 2 3 import android.app.Activity; 4 import android.hardware.Camera; 5 import android.hardware.Camera.Parameters; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button;10 import android.widget.Toast;11 12 public class MainActivity extends Activity {13 14 private boolean isopen = false; //記錄手電筒狀態15 private Camera camera; //16 private Button btn_flash;17 18 @Override19 protected void onCreate(Bundle savedInstanceState) {20 // TODO Auto-generated method stub21 super.onCreate(savedInstanceState);22 setContentView(R.layout.activity_main);23 24 btn_flash = (Button) findViewById(R.id.btn_flash);25 btn_flash.setOnClickListener(new OnClickListener() {26 @Override27 public void onClick(View v) {28 if (!isopen) { //如果手電筒已經開啟29 Toast.makeText(getApplicationContext(), "手電筒已開啟", 0).show();30 camera = Camera.open();31 Parameters params = camera.getParameters();32 params.setFlashMode(Parameters.FLASH_MODE_TORCH);33 camera.setParameters(params);34 camera.startPreview(); // 開始亮燈35 isopen = true;36 btn_flash.setText("手電筒已開啟!");37 } else {38 Toast.makeText(getApplicationContext(), "關閉了手電筒",39 Toast.LENGTH_SHORT).show();40 camera.stopPreview(); // 關掉亮燈41 camera.release(); // 關掉照相機42 isopen = false;43 btn_flash.setText("手電筒已關閉!");44 }45 }46 });47 }48 49 }
Android 手電筒開發原始碼