How to turn on/off camera LED / flashlight in Android
By mkyong | Last updated: August 29, 2012
Viewed: 176,240 (+81 pv/w)
In this tutorial, we show you how to turn on/off the phone camera led or flashlight in Android. See code snippets :
1. Turn on
2. Turn off
And, put following permission on AndroidManifest.xml .
P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
1. Android Layout
2. Activity
Read the code, a button to turn on / off the flashlight, it should be self-explanatory.
3. Android Permission
Assign CAMERA permission.
4. Demo
None, until i have 2nd hand phone to capture the current flashlight on my phone рџ™‚
Download Source Code
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Comments
Hello sir
How to make online examination system in android.
Please help me
when we open the flashlight , camera is blocked ..
how can I open flashlight and camera at same Time ?
Thanks u so much dear sir
please am having some little problem in my coding i don’t know if it is from my android studio setup or the way i code it,
if i type in your code by my self into my androidManifest.xml it will show me red on some code saying can not resolve
it happen on this codes:
camera = Camera.open();
final Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
the .open(), .getParameters(), .setParameters();, .stopPreview();
this are the code that will be coloured with red saying can not be resolve etc
and if i copy past it they will all be OK. but the R will be saying can not be resolve why
please and solution.
May be u’ll need to import the camera class file., then all of its methods can be resolved.
When i go back from the application of flashlight the light will by still be ON (i mean to say that torch app will still be running in the background).How to stop this session when i go back from this app?
Could I use this for a front facing camera to show the LED Lights for notifications instead?
Thank you for creating this tutorial. It’s my first app (besides “hello world”). It works well on my Galaxy S2.
Thank you! This was very helpful.
Alright I’m Just done with this. I don’t know how to use that codeing
I have a keyonca echoand when I try a flashlight
App it just flashes. I need a constant beam not a strobe!
the app run but the flash don’t work
How to turn flash led without opening camera ..
Actually i am making an led torch app in android and i want to turn flash on without opening camera so is it possible to make such an app.
Waiting for ur reply
Thanxx
I have to turn on camera flash using openCV. I need to use NativeCameraView but it doesn’t work.
can I open the flash using NativeCameraView in opencv? I tried but it doesn’t work.
Good answer back in return of this query with solid arguments and describing the whole thing concerning that.
What’s up friends, how is everything, and what you want to say concerning this piece of writing, in my view its in fact awesome designed for me.
really thanks for your help рџ‰
If you have recently lost or broke a flashlight, or if you are in the market for a new, better brand, then you are probably facing a lot of decisions about what kind of flashlight to purchase, and what will work best for your various needs. LED flashlights have risen in popularity, as have batteryless flashlights. :”
With best thoughts
The digital age has taken the world by storm, with the introduction of the camera phone, photo digital imagery tools are at the fingertips of consumers today because they are built-in to low end and high end styled cellular devices that are the rage with American all over the country.’
Go and visit our very own website too
Hi,
I am new to android and have an issue with my GT-N7100 phone that force closes whenever I start the camera app. Any camera flashlight app also does not run and closes with error. I believe some app or firmware is missing or corrupted on my phone. Code to check camera firmware version also force closes with error. Since you seem to be an expert on the android environment, was wondering if you could help point me to where to looks for the necessary files to be able to operate the camera and flash. Thanks in advance.
Not work on Samsung glaxay. not the torch is on and not off. just a buuton on screen is show.
Try to write this line:
camera.setPreviewTexture(new SurfaceTexture(0));
after this one:
camera = Camera.open();
This one requires API 11, so you should have this line in AndroidManifest.xml
I have noticed that method does not working on Motorola Razr/Droid Razr under ICS.
Any ideas how to fix it?
[…] Camera flashlight example You may interest on this example – How to turn on/off camera LED/flashlight in Android. […]
Hi i tried this on both avd and my galaxy s3. In my s3 it doesn’t install. and in the avd it doesn’t support flashlight. my s3 is 4.0.4, i adjusted the minSDK to 13 and Target to 14, still doesnt install. what am I doing wrong
Really u r an expert who can solve mind blowing problems.. I will keep asking u more stuff in the future.. Thank u for ur support.!
Hello Mkyong;
Please contact me рџ™‚
I have tried my best to follow your tutorial about using the camera LED as a flashlight but the problem I am having is with the device support, I would like for it to being once the user has clicked the torch. By default the code you have made checks to see if the device has a LED as soon as the application begins which isn’t my objective, could you please tell me how I could make an alert message for users that don’t have a built-in LED as soon as they have clicked the button “torch”. I am totally hopeless at java & I know that you’re a busy person but this needs to be resolved urgently. If you would like more detailed information about the problem please send me a message through Facebook, I would more then happy to provide you with a short video of the application running on a real device which could explain the problem in more depth.
I hope to hear from you soon,
thanks.
Источник
Работа с камерой в Android
Работа с камерой на телефоне всегда представляла для меня интерес. Как же это все устроено… И вот мне в руки попал телефон с Android’ом. Я не преминул возможностью попробовать разобраться в этом. Вот что получилось в итоге.
Рассмотрим небольшую программу, которая позволяет делать снимки.
Все операции проводятся с помощью класса Camera.
Необходимо завести переменную
и инициализировать ее
После завершения работы с камерой необходимо сделать
в противном случае камера останется заблокированной и недоступной для других приложений.
Для обычных приложений типа фотокамеры инициализацию лучше всего производить в onResume, а освобождение в onPause.
Обязательным условием при работе с камерой является создание окна предпросмотра (preview). Это окно должно являться объектом класса Surfaceи для отображения на экране подходит SurfaceView.
Объявим
Чтобы задать preview, необходимо вызвать метод setPreviewDisplay, параметром которого является объект класса SurfaceHolder.
Чтобы включить отображение preview, вызываем
Если этого не сделать, то камера не сможет делать снимки.
Собственно для того, чтобы сделать снимок, необходимо вызвать метод
С помощью параметров (кстати, любой из них может быть null) задаются обработчики разных событий:
- shutter — вызывается в момент получения изображения с матрицы
- raw — программе передаются для обработки raw данные (если поддерживается аппаратно)
- postview — программе передаются полностью обработанные данные (если поддерживается аппаратно)
- jpg — программе передается изображение в виде jpg. Здесь можно организовать запись изображения на карту памяти.
Вызов takePicture можно поместить непосредственно в обработчик onClick кнопки — в этом случае фотографирование произойдет сразу после нажатия на нее, но можно и воспользоваться предварительной автофокусировкой.
В этом случае задается обработчик Camera.AutoFocusCallback, в котором необходимо реализовать метод
Тогда после вызова в обработчике нажатия на кнопку camera.autoFocus(), однократно будет вызван обработчик, в котором мы уже и примем решение об удачной фокусировке и необходимости сделать снимок.
Для работы с SurfaceHolder можно задать SurfaceHolder.Callback
surfaceHolder.addCallback();
В этом случае необходимо реализовать методы
C помощью них приложению будет сообщаться о том, что Surface успешно создано, если оно изменено или то, что оно удалено.
Размер нашего preview можно менять в процессе выполнения программы:
Для приложения камеры удобнее всего сразу задать расположение экрана как
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
В противном случае нам придется, например, в surfaceCreated проверять расположение экрана и поворачивать preview с помощью, например, camera.setDisplayOrientation(0) .
Это не очень удобно, потому что поворот экрана занимает какое-то время. В этот момент происходит вызов onPause и onResume, пересоздается Surface.
Также имеется возможность объявить обработчик Camera.PreviewCallback, с помощью которого путем реализации метода
можно получать и обрабатывать каждый кадр, отображаемый в preview.
И последний важный момент. Чаще всего получается так, что отношение сторон SurfaceView отличается от отношения сторон в preview камеры. Поэтому для того, чтобы избежать искажений изображения на экране, необходимо подкорректировать размер отображаемого окна предпросмотра.
Чуть не забыл. В манифест необходимо добавить permission
MainScreen.java
main.xml
AndroidManifest.xml
Программа отлаживалась и тестировалась на телефоне LG Optimus One P500.
При написании использовались следующие источники информации:
Источник
Android camera off on
* HDR: яркие цвета и богатая детализация, фотографии выглядят как снятые профессиональным фотоаппаратом с обработкой:
* Panorama: до 360 градусов, до 100 MPix;
* Удаление нежелательных объектов одним нажатием;
* Ночной режим: съемка четких фотографий при любом освещении;
* Групповой портрет: выбор наиболее удачных лиц из серии групповых фотографий;
* Видеозапись;
* Pre-shot: Съемка кадров до момента нажатия;
* Фотопоследовательность: съемка динамических сцен;
* Burst и Экспо-брекетинг: профессиональные функции в мобильной камере;
* Съемка по таймеру
+ полный доступ ко всем настройкам, контролам и функциям камеры
Забудьте про десятки приложений камер. A Better Camera делает все что вам надо!
Топовые приложения камеры, такие как HDR Camera+, Night Camera+ и HD Panorama+ эволюционировали в A Better Camera — лучшую полнофункциональную камеру.
Приложение открыто для сторонних разработчиков, чтобы вобрать в себя опыт работы с изображением всего Android сообщества.
Соответствующие режимы A Better Camera бесплатны для пользователей HDR Camera+ и HD Panorama+.
Присоединяйтесь к нам на facebook: http://www.facebook.com/abettercam
версия: 3.52 GP Сообщение №1553, автор And_RU
версия: 3.51 GP Сообщение №1494, автор And_RU
версия: 3.50 Unlocked (Paid) A Better Camera (Пост Alex0047 #67505640)
версия: 3.50 GP A Better Camera (Пост алекс12 #67506522)
версия: 3.49 GP A Better Camera (Пост And_RU #67404079)
версия: 3.49 Unlocked (Paid) A Better Camera (Пост Alex0047 #67439070)
версия: 3.48 Unlocked (Paid) A Better Camera (Пост Alex0047 #64981529)
версия: 3.48 GP A Better Camera (Пост And_RU #64900015)
версия: 3.46 Unlocked A Better Camera (Пост Alex0047 #60086447)
версия: 3.46 GP A Better Camera (Пост And_RU #60060944)
версия: 3.45 Unlocked A Better Camera (Пост Alex0047 #59490218)
версия: 3.45 GP A Better Camera (Пост And_RU #59489868)
версия: 3.43 Unlocked A Better Camera (Пост Giacomino #58370564)
версия: 3.44 GP A Better Camera (Пост And_RU #59404015)
версия: 3.43 GP A Better Camera (Пост алекс12 #58336040)
версия: 3.42 Unlocked A Better Camera (Пост Anais10 #57380460)
версия: 3.42 GP A Better Camera (Пост алекс12 #57338038)
версия: 3.41 Unlocked A Better Camera (Пост Alex0047 #53302848)
версия: 3.41 build 122 GP A Better Camera (Пост алекс12 #53122645)
версия: 3.40 Unlocked A Better Camera (Пост Alex0047 #51044088)
версия: 3.40 GP A Better Camera (Пост алекс12 #51114878)
версия: 3.39 build 116 GP A Better Camera (Пост алекс12 #49008944)
версия: 3.39 build 98 Unlocked A Better Camera (Пост Alex0047 #49008056)
версия: 3.38 GP A Better Camera (Пост алекс12 #48498104)
версия: 3.37 build 96 Unlocked A Better Camera (Пост Alex0047 #47597500)
версия: 3.37 GP A Better Camera (Пост алекс12 #47592192)
версия: 3.36 Build 110 Google Play A Better Camera (Пост алекс12 #44281607)
версия: 3.36 Build 95 Unlocked A Better Camera (Пост Kamachi #44278612)
версия: 3.36 Build 93 Unlocked A Better Camera (Пост Giacomino #43852074)
версия: 3.34 Build 103 Google Play A Better Camera (Пост алекс12 #41559692)
версия: 3.35 Build 91 Unlocked A Better Camera (Пост Alex0047 #42694777)
версия: 3.34 Build 90 Unlocked A Better Camera (Пост Alex0047 #41527819)
версия: 3.32 Google Play A Better Camera (Пост алекс12 #39073230)
версия: 3.33 Unlocked A Better Camera (Пост Alex0047 #40764116)
версия: 3.32 Unlocked A Better Camera (Пост Alex0047 #39073335)
версия: 3.31 Unlocked A Better Camera (Пост Alex0047 #38002440)
версия: 3.30 Unlocked A Better Camera (Пост #37394159)
версия: 3.29 Unlocked A Better Camera (Пост #36895353)
Widget v1.7: //4pda.to/forum/d…3/ABC_Vidzhet__1.7.apk
версия: 3.28 Unlocked A Better Camera (Пост #36273399)
версия: 3.27 Unlocked A Better Camera (Пост #35348346)
версия: 3.26 Unlocked A Better Camera (Пост #35161581)
версия: 3.25 Unlocked A Better Camera (Пост #35034891)
версия: 3.24 Unlocked A Better Camera (Пост #32681571)
версия Unlocked v3.22 (Paid): //4pda.to/forum/d…mera+Unlocked_3.28.apk
версия: 3.23 Paid //4pda.to/forum/d…etter_Camera__3.22.apk
версия: 3.22 //4pda.to/forum/d…etter_Camera__3.22.apk
версия: 3.21 //4pda.to/forum/d…etter_Camera__3.21.apk
Widget v1.5: //4pda.to/forum/d…7/ABC_Vidzhet__1.5.apk
версия Unlocked v3.21 (Paid): A Better Camera (Пост #31636107)
версия: 3.20 //4pda.to/forum/d…etter_Camera__3.20.apk
версия Unlocked v3.20 (Paid): A Better Camera (Пост #31528021)
версия: 3.19 //4pda.to/forum/d…etter_Camera__3.19.apk
версия Unlocked v3.18 (Paid): A Better Camera (Пост #30427901)
A Better Camera Widget v1.2: A Better Camera (Пост #29693171)
A Better Camera Unlocked v3.1.7 (Paid): A Better Camera (Пост #30015863)
версия: 3.14 A Better Camera v3.14.apk ( 7.13 МБ )
версия: 3.15 Unlocked //4pda.to/forum/dl/post/4112505/A+Better+Camera+Unlocked+v3.1.5.apk
версия: 3.15 A Better Camera (Пост #28163258)
A Better Camera Unlocked v3.1.6 (Paid): A Better Camera (Пост #29593580)
Сообщение отредактировал iMiKED — 19.04.21, 05:38
Источник