Implement Step 1. Modify the layout file code activity_main.xml
1 <LinearLayoutxmlns: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 <Button8 Android:id= "@+id/btn_flash"9 Android:layout_width= "Match_parent"Ten Android:layout_height= "Wrap_content" One Android:text= "Flashlight is OFF!" "/> A - </LinearLayout>
2. Add the permissions you need to use in Androidmanifest.xml
1 <!--Camera, Flashlight -2 <uses-permissionAndroid:name= "Android.permission.CAMERA" />3 <uses-permissionAndroid:name= "Android.permission.FLASHLIGHT" />4 <uses-featureAndroid:name= "Android.hardware.camera" />5 <uses-featureAndroid:name= "Android.hardware.camera.autofocus" />6 <uses-featureAndroid:name= "Android.hardware.camera.flash" />
- Android.permission.CAMERA:Required to is able to access the CAMERA device.
- Android.permission.FLASHLIGHT:Allows access to the flashlight
3. Modify Mainactivity
1 Packagecom.example.test;2 3 Importandroid.app.Activity;4 ImportAndroid.hardware.Camera;5 Importandroid.hardware.Camera.Parameters;6 ImportAndroid.os.Bundle;7 ImportAndroid.view.View;8 ImportAndroid.view.View.OnClickListener;9 ImportAndroid.widget.Button;Ten ImportAndroid.widget.Toast; One A Public classMainactivityextendsActivity { - - Private BooleanIsOpen =false;//Record Flashlight Status the PrivateCamera camera;// - PrivateButton Btn_flash; - - @Override + protected voidonCreate (Bundle savedinstancestate) { - //TODO auto-generated Method Stub + Super. OnCreate (savedinstancestate); A Setcontentview (r.layout.activity_main); at -Btn_flash =(Button) Findviewbyid (r.id.btn_flash); -Btn_flash.setonclicklistener (NewOnclicklistener () { - @Override - Public voidOnClick (View v) { - if(!isopen) {//If the flashlight is turned on inToast.maketext (Getapplicationcontext (), "Flashlight turned on", 0). Show (); -Camera =Camera.open (); toParameters params =camera.getparameters (); + Params.setflashmode (parameters.flash_mode_torch); - camera.setparameters (params); theCamera.startpreview ();//Start Light *IsOpen =true; $Btn_flash.settext ("Flashlight is turned on! ");Panax Notoginseng}Else { -Toast.maketext (Getapplicationcontext (), "Turn off the flashlight", the toast.length_short). Show (); +Camera.stoppreview ();//Turn off the lights . ACamera.release ();//turn off the camera theIsOpen =false; +Btn_flash.settext ("Flashlight is off! "); - } $ } $ }); - } - the}
Android Flashlight Development Source code