I have one question that can we access android device camera's flash light
programmically.Is this possible to turn on and off flash light programmically?
please give me my answer .
thanks in advance.
package com.thedevelopersinfo.tutorial.android.soundrecordingexample;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
private MediaRecorder mediaRecorder;
private File file = null;
static final String PREFIX = "record";
static final String EXTENSION = ".3gpp";
private Button b1;
Camera mCamera;
public boolean isOn=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = Camera.open();
Camera.Parameters params = mCamera.getParameters();
b1=(Button)findViewById(R.id.startBtn);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setFlashlight();
}
});
}
public void setFlashlight()
{
if (mCamera == null)
{
}
Camera.Parameters params = mCamera.getParameters();
String value;
if (isOn) // we are being ask to turn it on
{
value = Camera.Parameters.FLASH_MODE_TORCH;
}
else // we are being asked to turn it off
{
value = Camera.Parameters.FLASH_MODE_AUTO;
}
try{
params.setFlashMode(value);
mCamera.setParameters(params);
String nowMode = mCamera.getParameters().getFlashMode();
if (isOn)
{
nowMode.equals(Camera.Parameters.FLASH_MODE_TORCH);
}
if (!isOn)
{
nowMode.equals(Camera.Parameters.FLASH_MODE_AUTO);
}
}
catch (Exception ex)
{
}
}
}
but i got following exception
03-10 18:47:34.907: ERROR/QualcommCameraHardware(1280): Parameter AntiBanding is not supported for this sensor
You can do so by using Camera.Parameters.setFlashMode. See: http://developer.android.com/reference/android/hardware/Camera.Parameters.html
it is possible. first you have to get the properties of hardware camera.using below method.
String flattenString;
camera = Camera.open();
Camera.Parameters param = camera.getParameters();
flattenString = param.flatten();
where flatten can give u a parameter string with key value pair.
you have to split it by "," and find the flash-mode key and its value
then apply this parameter in below method
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("Key", value);
where your key is "flash-mode"
and value is "On"
and then add this parameters to setParameters method and start your camera preview
mCamera.setParameters(parameters);
mCamera.startPreview();
your flash light is now ON.
Related
Following is the code for my app for a flash light
Its size comes out to be 1.4 MB which is too huge .
So i used progaurd to reduce size which ends up in 750 KB which is still huge as compared to code i am using.
Why the size is large ? and how to reduce it ? or i have made some mistake
package com.example.torch;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button power;
int flag=0;
public Camera camera;
private boolean hasFlash;
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onStop() {
super.onStop();
try{
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power=(Button)findViewById(R.id.button1);
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.show();
return;
}
camera = Camera.open();
Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
flag = 1;
power.setText("Power On");
power.setBackgroundColor(Color.BLUE);
power.setTextColor(Color.WHITE);
power.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (flag==0) {
camera = Camera.open();
Camera.Parameters p = camera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
flag = 1;
power.setText("Power On");
power.setBackgroundColor(Color.BLUE);
}
else
{
camera.stopPreview();
camera.release();
camera = null;
flag=0;
power.setText("Power Off");
power.setBackgroundColor(Color.BLACK);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You are extending AppCompatActivity, this means that your project includes Android Support Library v7, if you don't care about material look on old Android versions, you can simply remove it. Check your build.gradle file to see which libraries are included as those libraries will make your apk file bigger.
Other causes of a large apk file might be:
Drawables
Assets
My objective is as simple as to have my own flashlight app; I have researched both the android developer site and stackoverflow quite thoroughly but seem to lack the connecting bits:
package my.torch;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.CompoundButton;
public class MainActivity extends Activity {
/* public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
*/
Camera mCamera;
CompoundButton mTorch;
Parameters camParams;
private Context context;
AlertDialog.Builder builder;
AlertDialog alertDialog;
public SurfaceView surfaceView;
public SurfaceHolder surfaceHolder;
public String flashMode = null;
/** A safe way to get an instance of the Camera object. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.mysurface);
surfaceHolder = surfaceView.getHolder();
context = MainActivity.this;
if(context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)){
mTorch = (CompoundButton) findViewById(R.id.toggleButton1);
}
else{
// should use Dialog
// tell the user that he has no camera
//showDialog(context, FLASH_NOT_SUPPORTED);
}
final Camera mCamera = Camera.open(0);
mTorch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("mTorch", "on");
Parameters camParams = mCamera.getParameters();
// params.setFlashMode( Parameters.FLASH_MODE_OFF )
camParams.setFlashMode( Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(camParams);
mCamera.startPreview();
flashMode = camParams.getFlashMode();
Log.e("mTorch", flashMode );
// The toggle is enabled
} else {
// The toggle is disabled
Log.e("mTorch", "off");
Parameters camParams = mCamera.getParameters();
// params.setFlashMode( Parameters.FLASH_MODE_OFF )
camParams.setFlashMode( Parameters.FLASH_MODE_OFF);
mCamera.setParameters(camParams);
mCamera.stopPreview();
flashMode = camParams.getFlashMode();
Log.e("mTorch", flashMode );
}
}
});
//mCamera.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onDestroy() {
super.onDestroy();
if (mCamera != null) {
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(camParams);
mCamera.stopPreview();
mCamera.release();
}
}
}
The logging happily reports that the flashmode is torch or off as intended, however: The flash does not torch at all.
I read that I needed a surfaceview so I added it but with 0 height.
As I did collect bits and pieces here and there the code is probably not beautiful, my apologies.
Any idea on what I'm missing out?
(this is for a Nexus 5, 4.4.2)
Did you add permission to access camera in your manifest file?
uses-permission android:name="android.permission.CAMERA"
I'm new to android and I'm trying to make an app that accesses the camera with zoom and an overlay. To implement zoom I used this:
add Zoom controls of Camera in Camera
I've tried to initialize "params" using this:
Zoom In & Out Custom Camera - Null Pointer Exception
After initialising params in the constructor I still get the error "params cannot be resolved to a variable"
Have I missed something?
Any help would be greatly appreciated.
MainActivity.java
package com.reidbailey.droidscope;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ZoomControls;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
int currentZoomLevel = 0, maxZoomLevel = 0;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean cameraview = false;
LayoutInflater inflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.cameraview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
inflater = LayoutInflater.from(getBaseContext());
View view = inflater.inflate(R.layout.overlay, null);
LayoutParams layoutParamsControl= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(view, layoutParamsControl);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(cameraview){
camera.stopPreview();
cameraview = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
cameraview = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.CAMERA_ZOOM_CONTROLS);
params = camera.getParameters();
if(params.isZoomSupported()){
maxZoomLevel = params.getMaxZoom();
zoomControls.setIsZoomInEnabled(true);
zoomControls.setIsZoomOutEnabled(true);
zoomControls.setOnZoomInClickListener(new OnClickListener(){
public void onClick(View v){
if(currentZoomLevel < maxZoomLevel){
currentZoomLevel++;
camera.startSmoothZoom(currentZoomLevel);
}
}
});
zoomControls.setOnZoomOutClickListener(new OnClickListener(){
public void onClick(View v){
if(currentZoomLevel > 0){
currentZoomLevel--;
camera.startSmoothZoom(currentZoomLevel);
}
}
});
}
else
zoomControls.setVisibility(View.GONE);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
cameraview = false;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SurfaceView
android:id="#+id/cameraview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ZoomControls
android:id="#+id/CAMERA_ZOOM_CONTROLS"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
It's because params is nowhere defined in your code, hence the compiler is complaining. You can declare your variable in place where you're using it, so just add Camera.Parameters in front of your variable name:
Camera.Parameters params = camera.getParameters();
or - if you want to have it accessible in the whole MainActivity, place it below Camera declaration in MainActivity:
Camera camera;
//add params
Camera.Parameters params;
While accepted answer is correct.
As, me, if you too, where here for "cannot resolve Camera.Parameters"
You need to import proper library.
import android.hardware.Camera;
in copy paste i had imported incorrectly
import android.graphics.Camera;
I wanted to build a flashlight app using the following code.
It's working on a friend's HTC Desire HD, but it isn't on my RAZR and a friend's Galaxy Nexus.
I also tried the solution with focus_mode_infinity, but there's still no success.
package com.example.flashlight;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Camera camera = null;
Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button OnOff = (Button)findViewById(R.id.Switch);
OnOff.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
if(camera == null) {
camera = Camera.open();
camera.startPreview();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
camera.setParameters(parameters);
}
else {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(parameters);
camera.release();
camera = null;
}
}
});
}}
I think FLASH_MODE_TORCH is not supported by RAZR, I've had the same issue with a customer reporting the same problem for one app (Flash not flashing).
What I suggest you is before setting the parameter to check if its supported:
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
// Mode supported good to go
}
after setting parameters of the camera use the below method:
camera.startPreview();
here camera is your Camera object.
i want to switch between the front and back cameras on a button click .
when any one of the camera's is open , i need to release it and open the other one .
could anyone tell me the block of code to switch ?
Thank you in advance . . . .
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/camera_btn"/>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/front_back_btn"/>
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Button01"
android:contentDescription="#string/app_name">
</ImageView>
<com.example.surfacecamera.CameraView
android:id="#+id/CameraView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
</RelativeLayout>
THIS IS MY ACTIVITY
and main java class is
package com.example.surfacecamera;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
public class MainActivity extends Activity implements OnClickListener, Camera.PictureCallback {
CameraView cameraView;
ImageView imv;
Button b2 ;
int cameraCount = 0;
int camIdx = 0;
Camera cam;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
Button pictureButton = (Button) this.findViewById(R.id.Button01);
Button b2 = (Button) this.findViewById(R.id.Button02);
imv = (ImageView) this.findViewById(R.id.ImageView01);
cameraView = (CameraView) this.findViewById(R.id.CameraView01);
cameraCount = Camera.getNumberOfCameras();
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
pictureButton.setOnClickListener(this);
}
// From the OnClickListener
public void onClick(View v)
{
cameraView.takePicture(null, null, this);
}
// From the Camera.PictureCallback
public void onPictureTaken(byte[] data, Camera camera)
{
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
imv.setImageBitmap(bmp);
String filename = "apicture.jpg";
File pictureFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + filename);
try
{
FileOutputStream pfos = new FileOutputStream(pictureFile);
bmp.compress(CompressFormat.JPEG, 75, pfos);
pfos.flush();
pfos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
and another class
package com.example.surfacecamera;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraView extends SurfaceView implements SurfaceHolder.Callback
{
SurfaceHolder mHolder;
int width;
int height;
Camera mCamera;
public CameraView(Context context, AttributeSet attrs)
{
super(context,attrs);
holderCreation();
}
public CameraView(Context context)
{
super(context);
holderCreation();
}
public void takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg)
{
mCamera.takePicture(shutter, raw, jpeg);
}
#SuppressWarnings("deprecation")
public void holderCreation()
{
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where to draw.
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
// If we aren't landscape (the default), tell the camera we want portrait mode
if (this.getResources().getConfiguration().orientation !=
Configuration.ORIENTATION_LANDSCAPE)
{
params.set("orientation", "portrait"); // "landscape"
// And Rotate the final picture if possible
// This works on 2.0 and higher only
//params.setRotation(90);
// Use reflection to see if it exists and to call it so you can support older versions
try {
Method rotateSet = Camera.Parameters.class.getMethod(
"setRotation", new Class[] { Integer.TYPE } );
Object arguments[] = new Object[] { new Integer(90) };
rotateSet.invoke(params, arguments);
} catch (NoSuchMethodException nsme) {
// Older Device
Log.v("CameraView","No Set Rotation");
} catch (IllegalArgumentException e) {
Log.v("CameraView","Exception IllegalArgument");
} catch (IllegalAccessException e) {
Log.v("CameraView","Illegal Access Exception");
} catch (InvocationTargetException e) {
Log.v("CameraView","Invocation Target Exception");
}
}
mCamera.setParameters(params);
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException exception)
{
mCamera.release();
mCamera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
width = w;
height = h;
// Now that the size is known, set up the camera parameters and begin the preview.
Camera.Parameters parameters = mCamera.getParameters();
//parameters.setPreviewSize(w, h);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}