Android Example Turn your camera flash light into a torch - also with Java code inside the B4A project

See attached project. I have created this simple torch (on / off) by making use of java code found on the web and compiling it with Simple Library Compiler. Library files inside the /files folder. Copy it to you additional library folder (fiddleAround.jar and FiddleAround.xml) and refresh libs --> select/enable FiddleAround in the libs tab

EDIT: JHSTORCH_v1.zip should hopefully address the issues raised in the posts below. Copy / replace fiddleAround.jar and fiddleAround.xml to/in your additional library folder. (23)

EDIT: JHSTORCH_v2.zip - just tidied up the buttons a bit. The library files are in the /files folder of the project.

You can also try this. It is a torch but also includes the ability to generate Morse codes via the camera flash.
 

Attachments

  • JHSTORCH_v1.zip
    23.3 KB · Views: 1,327
  • JHSTORCH_v2.zip
    117.3 KB · Views: 1,835
Last edited:

Johan Schoeman

Expert
Licensed User
Longtime User
@Johan Schoeman My phone have front flash, can I use your code to turn it on? Thanks.
Not sure if it will work @susu. You will have to try it and see if it does work or not. I don't have a devise with a front facing torch - so I cannot test it.
 

Inman

Well-Known Member
Licensed User
Longtime User
Android 6.0 has a new Flashlight API that allows accessing LED flash without touching camera. This is how Google describes it:
If a camera device has a flash unit, you can call the setTorchMode() method to switch the flash unit’s torch mode on or off without opening the camera device. The app does not have exclusive ownership of the flash unit or the camera device. The torch mode is turned off and becomes unavailable whenever the camera device becomes unavailable, or when other camera resources keeping the torch on become unavailable. Other apps can also call setTorchMode() to turn off the torch mode. When the last app that turned on the torch mode is closed, the torch mode is turned off.

You can register a callback to be notified about torch mode status by calling the registerTorchCallback() method. The first time the callback is registered, it is immediately called with the torch mode status of all currently known camera devices with a flash unit. If the torch mode is turned on or off successfully, the onTorchModeChanged() method is invoked.

Could you please make suitable changes to the code accordingly? I guess we need to have the old code as well for API Level < 23 and the new code for the rest.
 
Last edited:

GDO

Member
Licensed User
Longtime User
Hello,

Could you please add "....setPreviewTexture..." in your java code ?
I don't know how to define SurfaceTexture correctly.
Sorry.

B4X:
...
    import android.graphics.SurfaceTexture;
...
                                if (!Parameters.FLASH_MODE_TORCH.equals(flashMode))
                                {
                                        // Turn on the flash
                                        if (flashModes.contains(Parameters.FLASH_MODE_TORCH))
                                        {
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_ON);
                                                cameraParameters.setFocusMode(Parameters.FOCUS_MODE_INFINITY);
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                                                m_Camera.setParameters(cameraParameters);
                                                //
                              SurfaceTexture dummySurface = new SurfaceTexture(1);
                              m_Camera.setPreviewTexture(dummySurface); 
                                                //
                                                m_Camera.startPreview();
                                                flashMode = cameraParameters.getFlashMode();

error :

B4A version: 5.80
Parsing code. (0.02s)
Compiling code. (0.04s)
Compiling layouts code. (0.01s)
Generating R file. (0.47s)
Compiling generated Java code. Error
javac 1.7.0_01
src\gdohome\example\main.java:551: error: unreported exception IOException; must be caught or declared to be thrown
m_Camera.setPreviewTexture(dummySurface);
^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
 
Last edited:

GDO

Member
Licensed User
Longtime User
Hello,
Your program doesn't work with a NEXUS 5, for me.
Is it ok for you ?

:-(
 
Last edited:

Johan Schoeman

Expert
Licensed User
Longtime User
Hello,

Could you please add "....setPreviewTexture..." in your java code ?
I don't know how to define SurfaceTexture correctly.
Sorry.

B4X:
...
    import android.graphics.SurfaceTexture;
...
                                if (!Parameters.FLASH_MODE_TORCH.equals(flashMode))
                                {
                                        // Turn on the flash
                                        if (flashModes.contains(Parameters.FLASH_MODE_TORCH))
                                        {
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_ON);
                                                cameraParameters.setFocusMode(Parameters.FOCUS_MODE_INFINITY);
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                                                m_Camera.setParameters(cameraParameters);
                                                //
                              SurfaceTexture dummySurface = new SurfaceTexture(1);
                              m_Camera.setPreviewTexture(dummySurface);
                                                //
                                                m_Camera.startPreview();
                                                flashMode = cameraParameters.getFlashMode();

error :

B4A version: 5.80
Parsing code. (0.02s)
Compiling code. (0.04s)
Compiling layouts code. (0.01s)
Generating R file. (0.47s)
Compiling generated Java code. Error
javac 1.7.0_01
src\gdohome\example\main.java:551: error: unreported exception IOException; must be caught or declared to be thrown
m_Camera.setPreviewTexture(dummySurface);
^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error


I don't follow the reason why you want to add the preview texture. What are you trying to achieve by adding that?
 

Johan Schoeman

Expert
Licensed User
Longtime User
Hello,
Your program doesn't work with a NEXUS 5, for me.
Is it ok for you ?

:-(
I don't have a Nexus 5 so cannot help you with that. Browse the web and see if you can find a solution for the Nexus 5 and then amend the code to make it work.
 

DavideV

Active Member
Licensed User
Longtime User
Hello,

Could you please add "....setPreviewTexture..." in your java code ?
I don't know how to define SurfaceTexture correctly.
Sorry.

B4X:
...
    import android.graphics.SurfaceTexture;
...
                                if (!Parameters.FLASH_MODE_TORCH.equals(flashMode))
                                {
                                        // Turn on the flash
                                        if (flashModes.contains(Parameters.FLASH_MODE_TORCH))
                                        {
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_ON);
                                                cameraParameters.setFocusMode(Parameters.FOCUS_MODE_INFINITY);
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                                                m_Camera.setParameters(cameraParameters);
                                                //
                              SurfaceTexture dummySurface = new SurfaceTexture(1);
                              m_Camera.setPreviewTexture(dummySurface);
                                                //
                                                m_Camera.startPreview();
                                                flashMode = cameraParameters.getFlashMode();


1 error

Hi, i'm using this for SurfaceTexture....

B4X:
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.view.Surface;
import android.graphics.SurfaceTexture;
import java.util.List;
import     java.io.IOException;
import android.os.Build;

    Camera mCamera;
    Camera.Parameters mParameters;
    boolean Initialized;
   
    //try initialize the torch
    public Boolean InitTorch(int ApiLevel) {
    try {
        if (mCamera==null)
            {mCamera = Camera.open();}       
        if (mCamera!=null)
            {
            if (ApiLevel>10)
                {
                try {
                    mCamera.setPreviewTexture(new SurfaceTexture(0));
                } catch (IOException e) {
                    e.printStackTrace();}
                }
            mCamera.startPreview();
            Initialized = true;
            return true;}
        else
            {Initialized = false;
            return false;}
        }
    catch (Exception e)
        {e.printStackTrace();
        Initialized = false;
        return false;}
    }

This help on some new devices....
bye
 

GDO

Member
Licensed User
Longtime User
I don't follow the reason why you want to add the preview texture. What are you trying to achieve by adding that?
Hi,

Thank you for looking at my problem.

According to Android doc, "m_Camera.startPreview();" can not work without a preview texture.
Or, in fact, it could sometimes work on some device "not very clean".
Your program is working fine for me except on Nexus 5 which I believe is a "very clean device".

I hope adding a preview texture will make Nexus 5 working.
:(
 

GDO

Member
Licensed User
Longtime User
Hi, i'm using this for SurfaceTexture....

B4X:
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.view.Surface;
import android.graphics.SurfaceTexture;
import java.util.List;
import     java.io.IOException;
import android.os.Build;

    Camera mCamera;
    Camera.Parameters mParameters;
    boolean Initialized;
  
    //try initialize the torch
    public Boolean InitTorch(int ApiLevel) {
    try {
        if (mCamera==null)
            {mCamera = Camera.open();}      
        if (mCamera!=null)
            {
            if (ApiLevel>10)
                {
                try {
                    mCamera.setPreviewTexture(new SurfaceTexture(0));
                } catch (IOException e) {
                    e.printStackTrace();}
                }
            mCamera.startPreview();
            Initialized = true;
            return true;}
        else
            {Initialized = false;
            return false;}
        }
    catch (Exception e)
        {e.printStackTrace();
        Initialized = false;
        return false;}
    }

This help on some new devices....
bye


Thank you.

I will try it tomorrow.

:)
 

GDO

Member
Licensed User
Longtime User
Thank you.

I will try it tomorrow.

:)
Thank you !

I was trying (post #25):

SurfaceTexture dummySurface = new SurfaceTexture(1);
m_Camera.setPreviewTexture(dummySurface);

but the error was :

src\gdohome\example\main.java:551: error: unreported exception IOException; must be caught or declared to be thrown
m_Camera.setPreviewTexture(dummySurface);
^

In fact, I must use try ... catch ... to solve the error like in your code. Thank you.

Now, there is no more error and I can try it on a Nexus 5 ...
 

GDO

Member
Licensed User
Longtime User
It works !!!

Thank you for your help DavideV.

For me, .zip code not working on Nexus 5.
.zip and setPreviewTexture working on Nexus 5 and Marshmallow.

@Johan Schoeman
Could you please, add setPreviewTexture in your .zip (with api level test)?

Here is the draft working code (for me):

B4X:
    public String TurnFlashOn(boolean turnOn)
    {
               String flashMode;
               flashMode = "";
               try
               {
                        m_Camera = Camera.open();
                        cameraParameters = m_Camera.getParameters();
                        List<String> flashModes = cameraParameters.getSupportedFlashModes();
                        flashMode = cameraParameters.getFlashMode();

                        if(turnOn == true)
                        {
                                if (!Parameters.FLASH_MODE_TORCH.equals(flashMode))
                                {
                                        // Turn on the flash
                                        if (flashModes.contains(Parameters.FLASH_MODE_TORCH))
                                        {
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_ON);
                                                cameraParameters.setFocusMode(Parameters.FOCUS_MODE_INFINITY);
                                                cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                                                m_Camera.setParameters(cameraParameters);

try{
    //All your IO Operations
                //SurfaceTexture dummy = new SurfaceTexture(1);
                //m_Camera.setPreviewTexture(dummy);  
                m_Camera.setPreviewTexture(new SurfaceTexture(0));
}catch(IOException ioe){
    //Handle exception here, most of the time you will just log it.
}                                              

  
                              
                                                m_Camera.startPreview();
                                              

                                                flashMode = cameraParameters.getFlashMode();
                                        }
                                }
                        }
                        else

:)
 

dragonguy

Active Member
Licensed User
Longtime User
Can i set ON flash 50ms, and then set OFF 500ms. i use timer to do this routine but fail, feel blinking too slow.
here is my example code:
B4X:
Sub Process_Globals
    Dim timer1 As Timer
    Dim count_ms=0 As Int
    Dim led_status=0 As Int
End Sub

Sub Globals
    Dim mf As B4Aflash
End Sub

Sub Activity_Create(firsttime As Boolean)
    Activity.LoadLayout("main")
    timer1.Initialize("timer1",50)
    timer1.enabled=True
End Sub

Sub timer1_Tick
   If led_status=0 Then
     mf.TurnFlashOn(True)
     led_status=1
   Else If led_status=1 Then
     count_ms=count_ms+1
     If count_ms=1 Then
       led_status=2
       mf.TurnFlashOff
     End If
   Else If led_status=2 Then
     count_ms=count_ms+1
     If count_ms=10 Then
       led_status=1
       count_ms=0
       mf.TurnFlashOn(True)
     End If
   End If
End Sub
 
Last edited:

Johan Schoeman

Expert
Licensed User
Longtime User
Can i set ON flash 50ms, and then set OFF 500ms. i use timer to do this routine but fail, feel blinking too slow.
here is my example code:
B4X:
Sub Process_Globals
    Dim timer1 As Timer
    Dim count_ms=0 As Int
    Dim led_status=0 As Int
End Sub

Sub Globals
    Dim mf As B4Aflash
End Sub

Sub Activity_Create(firsttime As Boolean)
    Activity.LoadLayout("main")
    timer1.Initialize("timer1",50)
    timer1.enabled=True
End Sub

Sub timer1_Tick
   If led_status=0 Then
     mf.TurnFlashOn(True)
     led_status=1
   Else If led_status=1 Then
     count_ms=count_ms+1
     If count_ms=1 Then
       led_status=2
       mf.TurnFlashOff
     End If
   Else If led_status=2 Then
     count_ms=count_ms+1
     If count_ms=10 Then
       led_status=1
       count_ms=0
       mf.TurnFlashOn(True)
     End If
   End If
End Sub
You might have to do it as in this example where the switching runs on a different thread

https://www.b4x.com/android/forum/t...ode-inside-the-b4a-project.48367/#post-316673

You will have to change the linline Java code....
 

dragonguy

Active Member
Licensed User
Longtime User
You might have to do it as in this example where the switching runs on a different thread

https://www.b4x.com/android/forum/t...ode-inside-the-b4a-project.48367/#post-316673

You will have to change the linline Java code....

I'm noob in java, i try to edit the code but always fail.
B4X:
public void TurnFlashOnOff()
    {
        for (int i=0; i<20; i++)
            {
                mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mCamera.setParameters(mParameters);
                mCamera.startPreview();
             
               try
               {
               Thread.sleep(50);
               } catch (InterruptedException e)
                   {
                 e.printStackTrace();
                }
              
                mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(mParameters);
             
                try
               {
               Thread.sleep(50);
               } catch (InterruptedException e)
                   {
                 e.printStackTrace();
                }
             
            }
            mCamera.release();
    }

error coode here:
B4X:
--------- beginning of main
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
Error occurred on line: 31 (Main)
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:131)
    at b4a.example.main._activity_create(main.java:394)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:710)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:339)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:249)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
    at b4a.example.main.afterFirstLayout(main.java:118)
    at b4a.example.main.access$000(main.java:33)
    at b4a.example.main$WaitForLayout.run(main.java:96)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5442)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera$Parameters.setFlashMode(java.lang.String)' on a null object reference
    at b4a.example.main.TurnFlashOnOff(main.java:914)
    ... 19 more
** Activity (main) Resume **
 
Last edited:
Top