I don't know how to detect a Volume Up/Down button press for 'n' seconds, so I would give an alternate solution. You would have to install Xposed Additions Pro and TeslaLED Flashlight. The former needs root access and Xposed Framework installed.
Instructions
- Visit my answer here. Under the heading "Instructions for Xposed Additions" follow steps 1-6.
- For step 7, choose Screen Off instead of others.
- Tap the newly created entry, activate Long Press by ticking the check-box, then tap on Long Press.
Scroll down and select Shortcut → TeslaLED Toggle. It will show a screen like:
(Click image to enlarge)
- Also, the delay of 2-3 seconds is way too large in my opinion. Anyhow, the app doesn't allow long press delay more than 500ms and you may configure in step 2 of my linked answer. I settled for 250ms.
You may use Tasker instead of using the TeslaLED app (officially recommended) but there is no guarantee that the native method would work. In fact, some users reported that even the latter app didn't work for them.
The action in Tasker to activate torch is Alert → Torch. It would show up in red color if it's not supported on your device.
There are some other ways mention in this Reddit thread which seems to be device specific but nonetheless could give you a lead for better web search results.
For example, in my One Plus One running CM12 there is no class named camera
let alone a file /sys/class/camera/flash/rear_flash
. But it does have a class leds
and the file /sys/class/leds/led:flash_torch/brightness
too. The default torch brightness in my device is set to 53 instead of 100.
I also tried the Tasker plugin AutoInput but it doesn't seem to support long press hardware buttons.