@@ -180,7 +180,10 @@ public static String detectTorchModePath() {
180180 }
181181 }
182182
183- public static boolean detectTorchMode (Context context ) {
183+ // 0: torch is off
184+ // 1: torch is on
185+ // -1: unable to detect (no root?)
186+ public static int detectTorchMode (Context context ) {
184187 SharedPreferences settings = context .getSharedPreferences (context .getPackageName (), Context .MODE_PRIVATE );
185188 String torchModePath = settings .getString (TORCH_MODE_PATH , "" );
186189
@@ -189,26 +192,34 @@ public static boolean detectTorchMode(Context context) {
189192 SharedPreferences .Editor editor = settings .edit ();
190193 editor .putString (TORCH_MODE_PATH ,torchModePath ).apply ();
191194 }
192- if ("N/A" .equals (torchModePath )) return false ; // torch mode file path detection has been performed (in another run or just now), and there were errors
195+ if ("N/A" .equals (torchModePath )) return - 1 ; // torch mode file path detection has been performed (in another run or just now), and there were errors
193196 else {
194197 try {
195198 StringBuilder sb = new StringBuilder ();
196199 int exitValue = RootHandler .executeCommandAndWaitFor ("cat " +torchModePath +"/brightness" , workDir , true , sb );
197200 if (exitValue != 0 ) {
198201 Log .e ("CTORCH" ,"no brightness file found under /sys/class/leds/" + torchModePath );
199- return false ;
202+ return - 1 ;
200203 }
201- return Integer .parseInt (sb .toString ().trim ()) != 0 ;
204+ return Integer .parseInt (sb .toString ().trim ()) == 0 ? 0 : 1 ;
202205 }
203206 catch (Exception e ) {
204207 e .printStackTrace ();
205- return false ;
208+ return - 1 ;
206209 }
207210 }
208211 }
209212
213+ /*
214+ when root is not available, current torch status can't be queried because /sys/class/leds is not accessible;
215+ in that case, just start assuming torch is off - this will result in having to press the torch button twice
216+ if you previously changed its status an odd number of times from outside this app/widget,
217+ i.e. from the system drop-down menu
218+ */
219+ public static boolean flashlightEnabled = false ;
210220 public static void toggleFlashlight (Context context ) {
211- boolean flashlightEnabled = detectTorchMode (context );
221+ int flashlightStatus = detectTorchMode (context );
222+ if (flashlightStatus >= 0 ) flashlightEnabled = flashlightStatus != 0 ;
212223
213224 CameraManager camManager = (CameraManager ) context .getSystemService (Context .CAMERA_SERVICE );
214225 String cameraId ;
@@ -223,6 +234,7 @@ public static void toggleFlashlight(Context context) {
223234 boolean b = !flashlightEnabled ;
224235 try {
225236 camManager .setTorchMode (cameraId , b );
237+ flashlightEnabled = b ;
226238 Toast .makeText (context , "Flashlight " +(b ?"ON" :"OFF" ), Toast .LENGTH_SHORT ).show ();
227239 }
228240 catch (Exception e ) {
0 commit comments