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);
Related
Android Studio 2.3.3 (LATEST)
Cocos2d-x 3.15.1 (LATEST)
I tested on Debug.
It's my first experience with Cocos2d-x Game Engine, I developed an Android Game using Cocos2d-x, all it's fine but when I tried to show the achievements it shows me an error like this :
java.lang.NullPointerException
at sonar.systems.framework.SonarFrameworkFunctions.showAchievements(SonarFrameworkFunctions.java:432)
at org.cocos2dx.lib.Cocos2dxRenderer.nativeTouchesEnd(Native Method)
at org.cocos2dx.lib.Cocos2dxRenderer.handleActionUp(Cocos2dxRenderer.java:129)
at org.cocos2dx.lib.Cocos2dxGLSurfaceView$10.run(Cocos2dxGLSurfaceView.java:311)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1486)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1263)
My Code when I click to show the achievements :
SonarCocosHelper::GooglePlayServices::showAchievements();
When I want To sign In :
java.lang.NullPointerException
at sonar.systems.framework.SonarFrameworkFunctions.isSignedIn(SonarFrameworkFunctions.java:277)
at org.cocos2dx.lib.Cocos2dxRenderer.nativeRender(Native Method)
at org.cocos2dx.lib.Cocos2dxRenderer.onDrawFrame(Cocos2dxRenderer.java:105)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1557)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1263)
My Code for Sign In :
if(!SonarCocosHelper::GooglePlayServices::isSignedIn())
SonarCocosHelper::GooglePlayServices::signIn();
My Manifest File :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ilyo.test"
android:installLocation="auto">
<supports-screens android:anyDensity="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-feature android:glEsVersion="0x00020000" />
<!-- Basic permission for Internet and don't allow turn of the screen -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:label="#string/app_name"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher">
<!-- Tell Cocos2dxActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="MyGame" />
<!-- Required for Google Play Services -->
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name="org.cocos2dx.cpp.AppActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Build Gradle File :
Cocos Helper Frameworks Used :
My Google Play Achievement (I removed the ID from this photo):
I searched already for solutions in relationship with Android Studio but the results are very rare, I don't know what is the solution and what this the reason for this error.
Thank you,
I founded a solution but now I guess it's just a dirty fix, first the problem is in the GooglePlayServices.java and exactly in onStart method : Null pointer Exception because mHelper is Null.
#Override
public void onStart()
{
mHelper.onStart((Activity) ctx);
}
Let us a little further why it generates null, so :
1. SonarFrameworkFunctions.java
when we want to call GooglePlayServices constructor from SonarFrameworkFunctions.java :
//GOOGLE PLAY SERVICES
if (SonarFrameworkSettings.USE_GOOGLE_PLAY_GAME_SERVICES)
{
String packageName = "sonar.systems.frameworks.GooglePlayServices.GooglePlayServices";
googlePlayServices = (InstantiateFramework(packageName) != null) ? InstantiateFramework(packageName) : new Framework();
}
2. Method : InstantiateFramework in SonarFrameworkFunctions.java
public static Framework InstantiateFramework(String packageName)
{
Framework tmp = null;
try
{
tmp = (Framework) Class.forName(packageName).getConstructor().newInstance();
tmp.SetActivity(((SonarFrameworkActivity) app));
} catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
Log.e("Class not found", "class doesn't exist or bad package name " + packageName);
}
return tmp;
}
The constructor is empty so there is only a method called onCreate that instantiate and prepare the mHelper to access to all functionalities of Google Play Services.
Solution (Dirty Fix):
GooglePlayServices.java
public GooglePlayServices()
{
mHelper=getGameHelper();
mHelper.setup(this);
}
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.
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 .
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>
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");
}
}
}