Why isn't my torch switching on?

87 views
Skip to first unread message
Assigned to leoh...@google.com by wuj...@google.com

Rodney McKay

unread,
May 17, 2023, 8:44:07 PM5/17/23
to Android CameraX Discussion Group
My imports include "import androidx.camera.core.TorchState" and two separate @Composable functions (one when the torch is on, another when it is off) are _successfully_ changing the state of the UI both in the emulator and on a connected physical phone (to show different colors on a power toggle switch), so I know that all my logic is correct.  I also know that the command "TorchState.ON" is being called correctly within that logic, it is just failing to actually switch the flash on.  It doesn't even blink, or flash once.  What am I missing?

My phone is running Android 8.0, and when I created the project in Android Studio I selected compatibility back to 7.0, so that shouldn't be a problem, should it?

Leo Huang

unread,
May 18, 2023, 3:40:28 AM5/18/23
to Android CameraX Discussion Group, pa...@reedyoung.net
Hi, 
Could you share your code about the part of CameraX? 
What is your test device model name? 
These help to speculate the problem. Thanks.

pa...@reedyoung.net 在 2023年5月18日 星期四上午8:44:07 [UTC+8] 的信中寫道:
Message has been deleted

Rodney McKay

unread,
May 18, 2023, 4:24:51 AM5/18/23
to Android CameraX Discussion Group, leoh...@google.com, Rodney McKay
device:  Samsung SM-G930U (Galaxy S7, snapdragon)

code:
package com.example.fireitup

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.camera.core.TorchState
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.fireitup.ui.theme.FireItUpTheme

class MainActivity : ComponentActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FireItUpTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    TorchState.ON
                    Greeting("Android")
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    FireItUpTheme {
        Greeting("Android")
    }
}

Leo Huang

unread,
May 18, 2023, 5:28:36 AM5/18/23
to Android CameraX Discussion Group, pa...@reedyoung.net, Leo Huang
Thanks for the code.
TorchState is just a state indicates the torch is currently opened or closed. It can be queried by CameraInfo.getTorchState().
To open torch by CameraX, you have to bind UseCase first and then invoke CameraControl.enableTorch(true).
If you just want to open torch without binding UseCase (e.g. w/o opening camera), see CameraManager.setTorchMode().
pa...@reedyoung.net 在 2023年5月18日 星期四下午4:24:51 [UTC+8] 的信中寫道:

Rodney McKay

unread,
May 18, 2023, 2:14:49 PM5/18/23
to Android CameraX Discussion Group, leoh...@google.com, Rodney McKay
Trying to implement your suggestion brings up another problem:  Android Studio (Flamingo, 2022.2.1) doesn't recognize the import directive "import com.example.phonyflashlight.databinding.ActivityMainBinding," specifically "databinding" is highlighted in red.

Following this guide (https://developer.android.com/codelabs/camerax-getting-started#1), I've added "viewBinding true" to the gradle file, and since that didn't work and there was a problem with "databinding" in MainActivity.kt, I added another line to the gradle, "dataBinding true" but that also hasn't helped.

Rodney McKay

unread,
May 18, 2023, 2:33:12 PM5/18/23
to Android CameraX Discussion Group, Rodney McKay, leoh...@google.com
Also, the rows
import com.example.phonyflashlight.ui.theme.Black
&
import com.example.phonyflashlight.ui.theme.PhonyFlashlightTheme

both work as expected so the problem is definitely with "databinding" not importing as these instructions describe, not anything that I did.  https://developer.android.com/codelabs/camerax-getting-started#1

Rodney McKay

unread,
May 18, 2023, 6:04:06 PM5/18/23
to Android CameraX Discussion Group, Rodney McKay, leoh...@google.com
In the meantime, I've created a CameraX UseCase within the logic I had already programmed, but it won't work until Google resolves the problem with their "databinding" tool not working properly.

Eino-Ville Talvala

unread,
May 18, 2023, 7:22:35 PM5/18/23
to Rodney McKay, Android CameraX Discussion Group, leoh...@google.com
If all you care about is using the flash as a flashlight, and not to actually run the camera to record images or video, you can simply use the OS's flashlight methods directly.
I haven't tested the code below, but it should be pretty close:

// find first camera with flash attached
String cameraIds = CameraManager.getCameraIdList();
String flashCameraId = null;
for (String id : cameraIds) {
   CameraCharacteristics c = CameraManager.getCameraCharacteristics(id);
   if (c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true) {
           flashCameraId = id;
           break;
      }
}
if (flashCameraId == null) {
   // show error about no flash unit on any camera
}
...
// turn on flash
...
// turn off flash

Then you don't need the camera permission, and you don't power on all the camera hardware for no reason.


--
You received this message because you are subscribed to the Google Groups "Android CameraX Discussion Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to camerax-develop...@android.com.
To view this discussion on the web visit https://groups.google.com/a/android.com/d/msgid/camerax-developers/ac79d661-88b2-4340-a212-66e8da3fa521n%40android.com.

Rodney McKay

unread,
May 18, 2023, 8:01:00 PM5/18/23
to Android CameraX Discussion Group, etal...@google.com, Android CameraX Discussion Group, leoh...@google.com, Rodney McKay
Thank you, that is very helpful!

Unfortunately, Build fails now but I think it must be something outside the scope of the CameraX (or Camera2 or Camera) libraries, because I'm looking right at the web page that describes how to use setTorchMode, and "android.hardware.camera2.CameraManager.setTorchMode(flashCameraId, true)" should at least execute, but Android Studio is rendering both "setTorchMode" and "flashCameraId" in red font.  I'll probably just uninstall/reinstall Android Studio, unless you recognize this kind of problem and know a simple solution.  If not, no worries.  This is my first Android project so there is nothing important in those directories.

Rodney McKay

unread,
May 19, 2023, 12:35:36 PM5/19/23
to Android CameraX Discussion Group, Rodney McKay, etal...@google.com, Android CameraX Discussion Group, leoh...@google.com
Uninstalling and reinstalling Android Studio didn't work so I'm wondering if I need to add an "implementation" line to gradle.build.  If so, where could I look that up, for my future reference?

I can tell what import line will be necessary in MainActivity.kt from the left side of the reference page for a Class (https://developer.android.com/reference/android/hardware/camera2/CameraManager#setTorchMode(java.lang.String,%20boolean) for example), but I don't see any resources describing what to do to a gradle file in general, to support different functionalities that might be wanted in an app.

Trevor McGuire

unread,
May 19, 2023, 1:41:59 PM5/19/23
to Rodney McKay, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
For the problem with "databinding" not being found, can you confirm that in your app's build.gradle, you have the namespace in the android {} block set to 'com.example.phonyflashlight'. Jetpack View binding will use this argument as the package for the generated view binding code.

Rodney McKay

unread,
May 19, 2023, 1:49:51 PM5/19/23
to Android CameraX Discussion Group, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com, Rodney McKay
Confirmed, and that is also the applicationId under defaultConfig.

Trevor McGuire

unread,
May 19, 2023, 2:02:22 PM5/19/23
to Rodney McKay, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
If you can share a project that exhibits your issues, without any code you don't want to share, we might be able to help you debug. You can create a zip file of a project from Android Studio by (File > Export > Export to Zip File...). A good way to share that file would be a Google drive link shared with the camerax-developers group.

Rodney McKay

unread,
May 19, 2023, 2:43:18 PM5/19/23
to Trevor McGuire, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
Does databinding require that the project includes a layout.xml file?  The reason I ask is, I just read something about how to edit layout.xml in order to use databinding, and this project was created without one, with the UI made using @Composable functions instead. 

Trevor McGuire

unread,
May 19, 2023, 5:18:24 PM5/19/23
to Rodney McKay, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
Oh I should have noticed from your code that you're using compose. Yes, View binding is meant to be used with Views and will generate code for each layout XML file you have. It is not intended to be used with Compose. If using Compose, you should set up your composables to handle interactions, such as clicking a torch on/off button. See https://developer.android.com/jetpack/compose/touch-input/handling-interactions

Rodney McKay

unread,
May 19, 2023, 5:23:26 PM5/19/23
to Android CameraX Discussion Group, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com, Rodney McKay
Awesome!  Then I am starting to learn my way around this development paradigm.  Have a nice weekend, and thank you all for the tips!

Rodney McKay

unread,
May 21, 2023, 1:07:58 AM5/21/23
to Android CameraX Discussion Group, Rodney McKay, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
After re-writing my code to use activity_main.xml instead of @Composables, I can again confirm the logic is working correctly by the changing appearance of the power button.  But when I un-comment the camera and torch commands, all the CameraManager commands are still failing, despite no errors or warnings about the line "import android.hardware.camera2.CameraManager, which is also not greyed out in Android Studio.  So why isn't Kotlin recognizing CameraManager just a few rows later?

val cameraIds: String = CameraManager.getCameraIdList() -- "getCameraIdList" is in red font
val c: CameraCharacteristics = CameraManager.getCameraCharacteristics(id) -- "getCameraCharacteristics" is in red font
android.hardware.camera2.CameraManager.setTorchMode(flashCameraId, true) -- "setTorchMode" is in red font


Is there an "implementation" line needed in build.gradle to correspond with the import line in MainActivity.kt?  Here is what I have so far in build.gradle's dependencies:

dependencies {
    def camerax_version = "1.1.0-beta01"
    implementation "androidx.camera:camera-core:${camerax_version}"
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"
    implementation "androidx.camera:camera-video:${camerax_version}"
    implementation "androidx.camera:camera-view:${camerax_version}"
    implementation "androidx.camera:camera-extensions:${camerax_version}"
    implementation 'androidx.core:core-ktx:1.8.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.1'
    implementation 'androidx.activity:activity-compose:1.7.1'
    implementation 'androidx.core:core-ktx:1.10.1'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    implementation 'androidx.compose.ui:ui-graphics'
    implementation 'androidx.compose.ui:ui-tooling-preview'
    implementation 'androidx.compose.material3:material3'
    implementation 'androidx.compose.material3:material3-window-size-class'
}

Rodney McKay

unread,
May 25, 2023, 12:46:45 AM5/25/23
to Android CameraX Discussion Group, Rodney McKay, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
I've nuked the android-studio directory and all hidden folders with configuration files and reinstalled from scratch, and the situation now is:

"import android.hardware.camera2.CameraManager"

...appears to be OK, all in "regular" color font for the UI theme I'm using currently.

But ALL calls to CameraManager functions in the program are still in red font and causes errors when I attempt to Build.

I realize this is a CameraX group, not Camera2, but I've already started this thread and at least some of you seem pretty familiar with Camera2 as well (no surprise that the same people would use both!), so I hope you guys don't mind me trying to solve this problem here.

Since reinstalling Android Studio, I've used SDK Manager to try 12L, 12.0, and 13.0, which was the default.  It doesn't seem like any older or newer SDK should work any better, as these are pretty recent but not experimental.  Agree?

Last week, somebody suggested sharing my code but the code I wrote is not the problem.  Something in Android Studio is (2022.2.1 Patch 1, running on Ubuntu 22.04).

Rodney McKay

unread,
May 25, 2023, 4:37:30 PM5/25/23
to Android CameraX Discussion Group, Rodney McKay, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
Now, I have also tried installing Android Studio on Windows 10.  The exact same problem occurs in Windows as in Linux.

What line(s) need(s) to be in gradle.build for android.hardware.camera2.CameraManager to be available to Kotlin?  That's really the only reasonable possible cause remaining for ALL the CameraManager commands not to be working.

Trevor McGuire

unread,
May 25, 2023, 5:24:12 PM5/25/23
to Rodney McKay, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com
In the code sample provided, you will need to replace CameraManager with an instance of CameraManager retrieved from a Context. For instance, if you are calling this from an Activity, you can use the activity as a Context to get the CameraManager (it's "this" below):

CameraManager cameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);

You can then use "cameraManager" in place of "CameraManager" (notice the capitalization) in the pseudo-code sample.

Let me know if that solves your issue.

Rodney McKay

unread,
May 26, 2023, 5:19:16 PM5/26/23
to Android CameraX Discussion Group, trevor...@google.com, Android CameraX Discussion Group, etal...@google.com, leoh...@google.com, Rodney McKay
[SOLVED]

Thanks for your patience, as well as the technical assistance itself!  If I had estimated that I would have copied & pasted anywhere near as much code as I have, I would have completed a few more CodeLabs before I posted!  And I will do that before I post here again -- if I do at all.  The mixes of Kotlin vs Java & of Compose vs layout.xml in the online tutorials are a bit daunting, and frustrating, but if I can get by on Composables going forward, maybe I'll stick with it.  Anyway, I'm glad I spent the time that I did, taking control of that little bit of the hardware and seeing how it's done.  Cheers!
Reply all
Reply to author
Forward
0 new messages