Android : Unable to start activity / Fail to connect to Camera service - android

I am trying to build an app which can turn on and off Camera Flash of my device . In Code its not showing any error but while launching the app on my device it's start to Crash .
Report bug is showing some Unable to start activity and something like Fail to connect Camera Services .
Since I am new in android Development and don't have enough knowledge.
I had already seen few questions regarding this but not able to find some useful information. All answers were approximately suggesting adding using permission in manifest file which I already did.
content of manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.joshiyogesh.flashlight">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
content of Main-activity Java:
package com.example.joshiyogesh.flashlight;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn;
android.hardware.Camera camera;
Camera.Parameters parameters;
boolean isFlash = false;
boolean isOn = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button2);
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
camera = Camera.open();
parameters = camera.getParameters();
isFlash = true;
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFlash){
if(!isOn){
btn.setText("Off");
btn.setBackgroundColor(Color.GREEN);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isOn = true;
}
else{
btn.setText("ON");
btn.setBackgroundColor(Color.RED);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isOn = false;
}
}
else{
Toast.makeText(MainActivity.this,"Camera Not detecting",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStop() {
super.onStop();
if(camera!=null){
camera.release();
camera = null;
}
}
}
I have uploaded image of report bug of my mobile device

I'm posting the code to open the camera,please make changes as per your need.
try this:
static Camera camera = null;
and declare the following:
try{
if(clickOn == true) {
clickOn = false;
camera = Camera.open();
Parameters parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
remoteViews.setViewVisibility(R.id.button1, View.GONE);
remoteViews.setViewVisibility(R.id.button2, View.VISIBLE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
clickOn = true;
camera.stopPreview();
camera.release();
camera = null;
remoteViews.setViewVisibility(R.id.button1, View.VISIBLE);
remoteViews.setViewVisibility(R.id.button2, View.GONE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
}
} catch(Exception e) {
Log.e("Error", ""+e);
}
After using camera, Don't forget to release it by following statement:
camera.release();
Also it may be the case that your app is not given permission to open camera at run time. Because from android 6.0 it is necessary to to have runtime permission to do specific tasks.
So if you are using Android 6.0(Marshmallow) or above, please check that the permission is enabled or not by following this:
The permission for camera could be disabled and should be enabled from the app settings. Settings -> Apps -> [Your App] -> Permissions.
That is what worked for me. Hope this help you too :)
EDIT
And please use e.printstacktrace() in your catch block to get error logcat.

i think there is problem while releasing the camera . Since you have written release method in onStop ,your camera will get release only when app is closed. try to release the camera when you are turning off the flash in button click method.

I got where i was wrong . Codes written above are Right . The only problem , i was using marshmallow in which we have to give permission to obtain camera permission through device .

Related

Camera Error "Can't Connect to the Camera" or in some phones the error appear "Camera is using by another app"

I have implemented to record audio in background using Android MediaRecorder if the audio recording is in progress and user open's the native camera to record video, it gives
Camera Error "Can't Connect to the Camera"
or on some phones, the error appears as
Your camera is in use by another application
If I stop mediarecorder then the native camera video recording works fine, I searched for events to know when Camera is going to start video so then in my app I stop the mediarecorder, I found the BroadcastReceiver with filters
<receiver android:name=".receiver.CameraReceiver">
<intent-filter android:priority="10000">
<action android:name="android.Medintent.action.CAMERA_BUTTON" />
<action android:name="android.hardware.action.NEW_PICTURE" />
<action android:name="android.hardware.action.NEW_VIDEO" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
</receiver>
NEW_VIDEO and NEW_PICTURE events fired when picture or video is captured and saved in the directory. Anyone knows how can this issue be solved? I want to know in my app the event when Native/Camera Apps going to record video. Thanks in advance
Even i had the same issue.
Once camera resource is being used by an application,untill it is released, you can use them in some other app or even a service.
If any service is using the camera resource, untill it releases the same we cannot use camera hardware.
You can doublecheck if camera hardware is being used using this code :-
private boolean isCameraInUse() {
Log.v(TAG, "isCameraInUse()");
boolean isCameraInUse = false;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)//Use Camera Api for Version Code < 23 and mCamera manager above it.
{
String cameraId = null;
CameraManager camManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
// Usually front mCamera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
Log.e(TAG, Log.getStackTraceString(e));
isCameraInUse = true;
}
try {
camManager.setTorchMode(cameraId, true);
camManager.setTorchMode(cameraId, false);
} catch (CameraAccessException e) {
Log.e(TAG, Log.getStackTraceString(e));
isCameraInUse = true;
}
} else {
Camera c = null;
try {
c = Camera.open();
} catch (RuntimeException e) {
Log.e(TAG, Log.getStackTraceString(e));
turnFlashOff(mContext);
isCameraInUse = true;
} finally {
if (c != null) c.release();
}
}
return isCameraInUse;
}
CameraManager.AvailabilityCallback provides onCameraAvailable(String cameraId) method to detect whether a camera is available or not.
https://developer.android.com/reference/android/hardware/camera2/CameraManager.AvailabilityCallback.html
Getting all camera IDs is the same as the above as shown by #GAGAN.
CameraManager camManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
// Usually front mCamera is at position 0.
try {
cameraId = camManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
Log.e(TAG, Log.getStackTraceString(e));
Log.cat("Error: ", e.getReason() + "");
if (e.CAMERA_DISABLED) { /* ENABLE CAMERA */ }
else if ( /* ... you can go to the link below to do various logic */ ) {
//...
}
else { /* do nothing */ }
}
https://developer.android.com/reference/android/hardware/camera2/CameraAccessException.html#CAMERA_IN_USE
Note: Until other applications use your camera hardware, they are using purposefully used by them. So until these apps don't free your hardware, you can't use that, it's clear. You can't know whether these apps actually need the camera. We believe process reserves hardware when it needs.
But, we can setup the listener on when camera becomes available (free) so that you can use it immediately.
CameraManager.AvailabilityCallback availabilityCallback = new CameraManager.AvailabilityCallback() {
#Override
public void onCameraAvailable(String cameraId) {
// your further stuffs. You must put all of your camera related logic here.
}
public void onCameraUnavailable(String cameraId) {
//you can logcat camera not available
}
};
The use of CameraManager.AvailabilityCallback abstract class is when you instantiate object, you do anonymous instantiation implementing callbacks like onCameraAvailable(), which is actually a listener that you are getting from the Camera Observer.
Answer: If you would have put your camera processing commands inside onCameraAvailable() callback, I guarantee, you wouldn't have got the error that you showed.
If the camera is used by other apps in the background, it means, those other apps are kind of buggy, because the camera needs foreground preview; they are not releasing the camera even after they are done with it. Nobody uses camera in background. Even in this case also, you are not supposed to kill camera process forcefully, because memory leaks can happen. Because you don't know how other processes are using the camera.

Android Turn on/off Camera Flash Programmatically with Camera2

I am making a simple application that acts as a flashlight. I need to be able to turn on and off the flash from a button in the application with the Camera2 API, as I get errors with the old camera API. I would like to use a "torch" flashlight, where the camera doesn't have to open in order for the flash to turn on. I know it's possible, as lots of phones have a flash on/off in the quick settings menu, but I can't find any code or tutorials about how to do this.
Code:
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
I am running on a Nexus 6P with Android 6.0.1.
EDIT: I need to use the Camera2 API. I haven't found a good tutorial for this yet, and after getting an answer, I will create one in Q/A format on here.
I'll be addressing you to the Android Dev. documentation about the CameraManager since more code will be required but this is the basic code to activate the Flash on the camera in API's above 21.
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, true);
Android CameraManager documentation.
Android.hardware.camera2 documentation.
very important thing to remember that you will need to use try/catch to discard possible errors and ofcourse check that no other higher priority application is using the camera at the moment.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
for (String camID : mCameraManager.getCameraIdList()) {
CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(camID);
int lensFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
mCameraId = camID;
break;
} else if (lensFacing == CameraCharacteristics.LENS_FACING_BACK && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
mCameraId = camID;
}
}
if (mCameraId != null) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
mCameraId will preferably turn on front camera flash by priority and if there is no front flash then back camera flash will be used. If device has no flash then mCameraId will be null and setTorchMode will not be called in the code above.
Try this. Is working fine on me for android Pie and above. There is a toggle button that turns on and off the flashlight
ToggleButton FlB = (ToggleButton) findViewById(R.id.FlashBt);
final boolean[] IsTurnedOn = {false};
final CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
final String finalCameraId = cameraId;
FlB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!IsTurnedOn[0]){
try {
camManager.setTorchMode(finalCameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
else {
try {
camManager.setTorchMode(finalCameraId, false);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
IsTurnedOn[0] =!IsTurnedOn[0];
}
});
Simplest and most banal way to do a flashlight app
// xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.torcia.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="#+id/flash_button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="turnOnOff"/>
</RelativeLayout>
//java code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button flashButton;
String buttonText;
public void checkState(String buttonText) {
switch (buttonText) {
case "ON":
flashButton.setText("OFF");
flashOn();
break;
case "OFF":
flashButton.setText("ON");
flashOff();
break;
}
}
public void turnOnOff(View view) {
flashButton = (Button) findViewById(R.id.flash_button);
buttonText = flashButton.getText().toString();
checkState(this.buttonText);
}
public void flashOn() {
Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
}
public void flashOff() {
Camera camera2 = Camera.open();
Camera.Parameters parameters2 = camera2.getParameters();
parameters2.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera2.setParameters(parameters2);
camera2.stopPreview();
}
}
// AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Auto launch an activity when beacon comes in a certain distance

I want my application to auto launch an activity when beacon comes within a certain distance (in my case it is 1 meter)
My activity gets launched when i plug in or plug off the charger and when i boot the device but it didn't get auto launch when i closed the application and beacon is in 1 meter.
what i want is if beacon is in 1 meter then activity should launch by itself.
I am using android beacon library and following the same steps mentioned on
https://altbeacon.github.io/android-beacon-library/samples.html
My manifest file code is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.altbeacon.beaconreference"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="org.altbeacon.beaconreference.MyApplicationName">
<activity
android:launchMode="singleInstance"
android:name="org.altbeacon.beaconreference.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My application class code is :
import java.util.Collection;
import android.app.Application;
import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import org.altbeacon.beacon.startup.RegionBootstrap;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
public class MyApplicationName extends Application implements BootstrapNotifier, RangeNotifier {
private static final String TAG = ".MyApplicationName";
private RegionBootstrap regionBootstrap;
private BeaconManager mBeaconManager;
private Region region;
private Region mAllBeaconsRegion;
private BackgroundPowerSaver mBackgroundPowerSaver;
private RegionBootstrap mRegionBootstrap;
#Override
public void onCreate() {
mAllBeaconsRegion = new Region("all beacons", null, null, null);
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBackgroundPowerSaver = new BackgroundPowerSaver(this);
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
//
Log.d(TAG, " region. starting ranging");
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
mBeaconManager.setBackgroundScanPeriod(11000l);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
mRegionBootstrap.disable();
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
try {
mBeaconManager.startRangingBeaconsInRegion(new Region("all beacons", null, null, null));
mBeaconManager.setRangeNotifier(this);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "Got a didEnterRegion call");
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
// TODO Auto-generated method stub
if (beacons.size() > 0) {
for (Beacon beacon: beacons) {
if(beacon.getDistance()<1)
{
Log.d(TAG, "within 1 minute call");
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
}
}
}
}
My Main activity class is:
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The behavior of the Android Beacon Library after an app is closed is different depending on how it was closed. Beacon scanning keep going at background rates (once every 5 minutes on Android 4.x) if you use the back button. If you kill it with the task switcher, it will resume scanning as soon vas possible (on power connected/disconnected or reboot).
Full details here: http://altbeacon.github.io/android-beacon-library/resume-after-terminate.html
Your code looks OK to do what you want within the parameters of what is described above. It is possible that you are simply seeing a five minute delay on detections when the app is in the background. Scanning once every five minutes in the background is done to save battery, but is configurable. On Android 5.x this delay is not present if you go from no beacons being visible to beacons being visible.
See here for details: http://altbeacon.github.io/android-beacon-library/battery_manager.html

Camera on Android emulator doesn't work

I'm a begginer android programmer and I have a problem with the camera. What I'm trying to do is to get a preview on the camera. The problem is, Camera.open() always returns null. The code goes like this:
CameraPreview.java
public class CameraPreview extends Activity implements SurfaceHolder.Callback
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_preview);
SurfaceHolder holder;
SurfaceView preview = (SurfaceView) findViewById(R.id.surface1);
holder = preview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Camera camera = Camera.open();
if(camera!=null)
{
try
{
camera.setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.paparazzi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CameraPreview"> </activity>
</application>
emulator config:
hw.lcd.density=240
hw.cpu.arch=arm
skin.name=WVGA800
sdcard.size=64M
abi.type=armeabi-v7a
hw.camera.back=emulated
image.sysdir.1=system-images\android-16\armeabi-v7a\
hw.gpu.enabled=yes
hw.camera.front=emulated
skin.path=platforms\android-16\skins\WVGA800
hw.cpu.model=cortex-a8
vm.heapSize=48
hw.ramSize=512
I use eclipse with android plugin and the newest sdk. I would really appreciate any suggestions.
before API version 14, the emulator doesn't support camera simulation. Even after the update the documentation doesn't really talk about it.
there is a workaround to this - check it out here.
http://www.tomgibara.com/android/camera-source
You haven't given following feature in the Manifest. Give it and run it again.
<uses-feature android:name="android.hardware.camera" android:required="true"/>
If still getting the Exception, put your Logcat output here.
Updated:
private static Camera camera;
public static Camera getCameraInstance(){
try {
camera = Camera.open();
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Toast.makeText(context, "Camera is occupied by another program" , Toast.LENGTH_SHORT).show();
}
return camera; // returns null if camera is unavailable
}
Use above code in your's and try to extract the exception if it getting again and again.
Call
CameraPreview.getCameraInstance();
inside your surfaceCreated method
Thanks #alextsc to remind me about the uses-feature
using android’s inbuilt camera app, launching the camera and taking the picture can done with very few lines of code using the power of Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

How to use camera flash/led as torch on a Samsung Galaxy Tab?

I'm facing to a problem with a Samsung Galaxy Tab. I want to use the camera flash as torch.
Does anyone know how to enable it ?
Hereby a code that works to enable/disable the camera flash on a HTC Desire but fails on Samsung Galaxy Tab.
FlashLight.java :
package com.example.FlashLight;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FlashLight extends Activity {
private final static String LOG_TAG = "FlashLight";
private Button mOnBtn;
private Button mOffBtn;
private Camera mCamera;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mOnBtn = (Button) findViewById(R.id.on_btn);
mOnBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
processOnClick();
}
});
mOffBtn = (Button) findViewById(R.id.off_btn);
mOffBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
processOffClick();
}
});
}
#Override
protected void onResume() {
super.onResume();
try{
mCamera = Camera.open();
} catch( Exception e ){
Log.e(LOG_TAG, "Impossible d'ouvrir la camera");
}
}
#Override
protected void onPause() {
if( mCamera != null ){
mCamera.release();
mCamera = null;
}
super.onPause();
}
private void processOffClick(){
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
}
}
private void processOnClick(){
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
}
}
}
AndroidManifest.xml :
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".FlashLight"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
</manifest>
layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/on_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Flash ON" />
<Button
android:id="#+id/off_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Flash OFF" />
</LinearLayout>
Thanks !
You aren't doing anything wrong. In fact, you are doing everything correct. You are encountering a Device-Specific issue that is very prevalent in the Android world. I have found the following behavioral patterns for FLASH_MODE_TORCH:
Works fine in all cases
Works fine, but not with autofocus on
Doesn't work at all
Frustratingly, getSupportedFlashModes() will return FLASH_MODE_TORCH on nearly every device when only a handful actually support it.
Also, some device implementations swizzle the supported flash modes. If you go through Camera.Parameters you can try setting the flash mode to FLASH_MODE_ON, FLASH_MODE_AUTO or FLASH_MODE_RED_EYE and see whether any of them work. Note - this is a device-specific hack.
I have filed these types of bugs with Google regarding the DroidX and Nexus S. They closed it as a device-specific issue. I would say to report this to Samsung in hopes for a driver or firmware fix, but their Android support channels do not exist.
Took me a while but I think you're missing a startPreview() there.
After you do your Camera.open() and after you set the parametrs, do a mCamera.startPreview(). That should do the trick.
This is how I made it work.
if (Build.MODEL.equals("GT-P1000")) {
Log.d(FlashlightActivity.TAG, "This is Samsung Galaxy Tab.");
params.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(params);
camera.startPreview();
camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
isLEDturnedOn = true;
Log.d(FlashlightActivity.TAG, "LED turned ON.");
}
This is how I turn on and of the torch in LG Nexus 4 and Samsung Galaxy Ace 2.
public void changeTorch() {
try {
camera = Camera.open();
// try to open the camera to turn on the torch
Camera.Parameters param = camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(param);
camera.startPreview(); // needed for some devices
Log.v("BSW torch", "Torch ON");
} catch (Exception e) {
// if open camera fails, try to release camera
Log.w("BSW torch", "Camera is being used trying to turn Torch OFF");
try {
camera.release();
} catch (Exception ex) {
Log.e("BSF torch", "Error releasing camera");
}
}
}

Categories

Resources