1. Use ihardwareservice for direct control
Android1.5 previously provided this interface directly. Later, we need to do it ourselves.
Create a new Android. OS package in your project and create an ihardwareservice. aidl file. The content is as follows:
[Java]
View plaincopy
- <Span style = "font-size: 18px;"> package Android. OS;
- /** {@ Hide }*/
- Interface ihardwareservice
- {
- // Obsolete flashlight support
- Boolean getflashlightenabled ();
- Void setflashlightenabled (Boolean on );
- } </Span>
Then introduce
[Java]
View plaincopy
- Import Android. OS. ihardwareservice;
- /**
- * Enable and disable the flashlight.
- * @ Param isenable
- * @ Author Linc
- * @ Date 2012-3-18
- */
- Private void setflashlightenabled (Boolean isenable)
- {
- Try
- {
- Method method = Class. forname ("android. OS. servicemanager"). getmethod ("getservice", String. Class );
- Ibinder binder = (ibinder) method. Invoke (null, new object [] {"hardware "});
- Ihardwareservice localhardwareservice = ihardwareservice. stub. asinterface (binder );
- Localhardwareservice. setflashlightenabled (isenable );
- }
- Catch (exception E)
- {
- E. printstacktrace ();
- }
- }
In this way, you can turn on the flashlight. Permissions to be used:
[HTML]
View plaincopy
- <Span style = "font-size: 18px;"> <uses-Permission Android: Name = "android. Permission. Flashlight"/>
- <Uses-Permission Android: Name = "android. Permission. hardware_test"/> </span>
2. Use a camera to control the flashlight
This is another direction of thinking. Camera comes with a variety of interfaces and parameters. We just need to use them.
[Java]
View plaincopy
- <Span style = "font-size: 18px;"> private camera = NULL;
- Private parameters = NULL;
- // Directly enable
- Camera = camera. open ();
- Parameters = camera. getparameters ();
- Parameters. setflashmode (parameters. flash_mode_torch); // enable
- Camera. setparameters (parameters );
- // Close directly
- Parameters. setflashmode (parameters. flash_mode_off); // close
- Camera. setparameters (parameters );
- Camera. Release (); </span>
If you encounter this problem, you can try the preview method of camera:
[Java]
View plaincopy
- Private void openlighton (){
- If (null = m_camera)
- {
- M_camera = camera. open ();
- }
- Camera. parameters = m_camera.getparameters ();
- Parameters. setflashmode (camera. Parameters. flash_mode_torch );
- M_camera.setparameters (parameters );
- M_camera.autofocus (new camera. autofocuscallback (){
- Public void onautofocus (Boolean success, camera ){
- }
- });
- M_camera.startpreview ();
- }
- Private void closelightoff (){
- If (m_camera! = NULL)
- {
- M_camera.stoppreview ();
- M_camera.release ();
- M_camera = NULL;
- }
- }