Here is a simple source code for making a flashlight:
1. xml layout:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/img_std" android:layout_width="fill_parent" android:layout_height="fill_parent" /></LinearLayout>
2. actity code:
Package COM. diecolor; 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. imageview; public class stdactivity extends activity {imageview; Boolean flag = false; camera; @ overrideprotected void oncreate (bundle savedinstancestate) {// Todo auto-generated method stubsuper. oncreate (savedinstancestate); setcontentview (R. layout. SDT); imageview = (imageview) findviewbyid (R. id. img_std); imageview. setimageresource (R. drawable. SDT); imageview. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubif (FLAG) {If (camera! = NULL) {Camera. stoppreview (); camera. release (); flag = false; imageview. setimageresource (R. drawable. SDT) ;}} else {Camera = camera. open (); // enable camera parameters = camera. getparameters (); parameters. setflashmode (parameters. flash_mode_torch); // enable camera. setparameters (parameters); camera. startpreview (); flag = true; imageview. setimageresource (R. drawable. sdtopen );}}});}}
3. permission settings
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" />
, 4, code parsing:
If camera is not empty, camera. stoppreview (); camera. Release ();
Set the flag value to flase and modify the image imageview. setimageresource (R. drawable. SDT );
Otherwise, open camera, camera = camera. open ();
Never forget to set parameters,
Parameters = camera. getparameters ();
Parameters. setflashmode (parameters. flash_mode_torch );
Camera. setparameters (parameters );