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.
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
I making a Flashlight app, and I use Fragments.
When I press the button, The lantern light delayed more than 4 seconds, and i don't know what happen.
Also, when I Press the switch button another time, the Flashlight doesn't turn off
Any idea?
Also I would like to make a stroboscopic lantern light with another button.
I search in internet but i dont find another option to make this feature, only this.
this is my code
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
public class HerramientasFragment extends Fragment {
private Camera cam;
private Switch linterna;
public HerramientasFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
cam = Camera.open();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View masterView = inflater.inflate(R.layout.fragment_herramientas, container, false);
linterna = (Switch) masterView.findViewById(R.id.switch_linterna);
linterna.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Switch liternaSwitch = (Switch) v;
Parameters p;
if (liternaSwitch.isChecked()) {
p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
} else {
p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
cam.stopPreview();
}
}
});
return masterView;
}
}
It is possible that the 4 second delay is hardware/operating system related and out of your control. That's not to say it can't be fixed, but I am unable to find anything related to it (Some Android experts might have a better idea here).
The light not turning off is probably because you need to add cam.release(); as mentioned in this answer.
As for a stroboscopic light, I found this tutorial. It seems to be almost exactly what you are looking for.
Just removing the line cam.startPreview() worked for me .
public void flashLightOn(){
p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
}
public void flashLightOff(){
p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
}
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 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.
I have yet to try this on an actual device, but expect similar results.
Anyway, long story short, whenever I run my app on the emulator, it crashes due to an out of memory exception.
My code really is essentially the same as the camera preview API demo from google, which runs perfectly fine.
The only file in the app (that I created/use) is as below-
package berbst.musicReader;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/*********************************
* Music Reader v.0001
* Still VERY under construction.
* #author Bryan
*
*********************************/
public class MusicReader extends Activity {
private MainScreen main;
#Override
//Begin activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = new MainScreen(this);
setContentView(main);
}
class MainScreen extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder sHolder;
Camera cam;
MainScreen(Context context) {
super(context);
//Set up SurfaceHolder
sHolder = getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// Open the camera and start viewing
cam = Camera.open();
try {
cam.setPreviewDisplay(holder);
} catch (IOException exception) {
cam.release();
cam = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Kill all our crap with the surface
cam.stopPreview();
cam.release();
cam = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Modify parameters to match size.
Camera.Parameters params = cam.getParameters();
params.setPreviewSize(w, h);
cam.setParameters(params);
cam.startPreview();
}
}
}
Make sure the camera permission is added in AndroidManifest.xml. Apparently you'll get an out of memory exception if you don't (for some bizarre reason). It worked for me, anyway.