App Freezes and Crashes when trying to Blink the Flashlight - android

there Folks! And Here it goes another Question.. from me..
I'm making a flashlight app. In the app there are two buttons, one is for turning on/off flash (flashlight_switch) and the other one is for blinking the flash With a single tap on the Button (sos_switch) at medium speed. The flash on/off works perfectly, but when i press the SOS button the app freezes and crashes. And also how can I turn off the SOS. I'm a beginner so it would be very nice that you explain the answer in depth. Please ignore Any typos if there are. The App is tested on Galaxy S3 and LG G3 and no luck on both of them.
Here is the complete code:
Java:
FlashlightActivity:
public class FlashlightActivity extends Activity {
ImageButton flashlight_switch;
ImageButton sos_switch;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
flashlight_switch = (ImageButton) findViewById(R.id.flashlight_switch);
sos_switch = (ImageButton) findViewById(R.id.sos_switch);
flashlight_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (Flash.getTorch()) {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_on);
} else {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_off);
}
}
});
sos_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (SOS.getSOS()) {
sos_switch.setImageResource(R.drawable.sos_on);
} else {
sos_switch.setImageResource(R.drawable.sos_off);
}
}
});
}
}
Flash:
class Flash {
private static boolean flashOnOff = false;
private static boolean sosOnOff = false;
public static Camera camera;
private static Camera.Parameters params;
public static boolean getTorch() {
if (flashOnOff)
off();
else
on();
return flashOnOff;
}
public static boolean getSOS() {
if (sosOnOff)
offSOS();
else
onSOS();
return sosOnOff;
}
private static void on() {
if (!flashOnOff) {
if (camera == null || params == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
int a = 10;
}
}
try {
camera.setPreviewTexture(new SurfaceTexture(0));
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
flashOnOff = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void off() {
if (camera == null || params == null)
return;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
camera = null;
flashOnOff = false;
}
private static void onSOS() {
Thread t = new Thread() {
public void run() {
try {
int delay = 50;
int times = 10;
for (int i=0; i < times*2; i++) {
if (flashOnOff) {
on();
} else {
off();
}
sleep(delay);
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
private static void offSOS() {
Thread t = new Thread();
t.stop();}}
Thanks In Advance!
Update:
I have updated my flash.java. It does not crash now but still the SOS don't work and also the sos switch freezes. I can't figure it out now. Please help!!!! as soon as possible!

You should not sleep Thread.sleep(blinkDelay); the thread because it is main thread need to update UI.you should use a different thread for SOS on
And Your SOS on function is in recursive infinite loop plz edit it. You are calling ON infinite time recursivly
Make Flash class ON / OFF method to public and make few changes in SOS's on method on(); to Flash.on and off to Flash .off
Flash.java
class Flash {
private static boolean flashOnOff = false;
public static Camera camera;
private static Camera.Parameters params;
static Thread t;
public static boolean getTorch() {
if (flashOnOff) // turn off flash
off();
else // turn on flash
on();
return flashOnOff;
}
private static void on() {
if (!flashOnOff) {
if (camera == null || params == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
int a = 10;
}
}
try {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
flashOnOff = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void off() {
if (camera == null || params == null)
return;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
flashOnOff = false;
}
public static void onSOS() {
t = new Thread() {
public void run() {
try {
int delay = 50;
while (true) {
if (t.isInterrupted())
break;
getTorch();
sleep(delay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
public static void offSOS() {
if (!t.isInterrupted()) {
t.interrupt();
off();
}
}}
FlashlightActivity.java
public class FlashlightActivity extends Activity {
ImageButton flashlight_switch;
ImageButton sos_switch;
boolean isStart = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
flashlight_switch = (ImageButton) findViewById(R.id.flashlight_switch);
sos_switch = (ImageButton) findViewById(R.id.sos_switch);
flashlight_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (Flash.getTorch()) {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_on);
} else {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_off);
}
}
});
sos_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isStart){
Flash.onSOS();
isStart = true;
sos_switch.setImageResource(R.drawable.sos_off);
}else{
Flash.offSOS();
isStart = false;
sos_switch.setImageResource(R.drawable.sos_on);
}
}
});
}
}

Related

how to implement button with flashlight blinking code in android studio

i want to add flashlight Blinking mode in android studio with a button. but i don't know that how can i put a code and how to implement this code with a button. because i want that if i press button then flashlight start blinking.
can anyone tell me that how can i implement this code with a button?
String[] list1 = { "1", "0", "1", "0", "1", "0", "1", "0", "1", "0" };
for (int i = 0; i < list1.length; i++) {
if (list1[i].equals("0")) {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
You can use this code for blink i make this as method :
private void BlinkFlash(){
String myString = "010101010101";
long blinkDelay =50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
} else {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and it will call like this :
BlinkMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BlinkFlash();
}
});
Hope this will work for you and yeah make string long if you want blink long time then
All of these below codes put inside any where in your activity/fragment:
Status, handler, Camera variables:
boolean isOn[] = {false};
boolean[] isBlinking = {false};
Handler handler = new Handler();
CameraManager camManager = null;
String cameraId = null;
Handle button click listener on your activity/fragment:
camManager = (CameraManager) view.getContext().getSystemService(Context.CAMERA_SERVICE);
buttonFlash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isBlinking[0]){
BlinkMode(view);
isBlinking[0] = true;
} else {
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
isBlinking[0] = false;
}
}
});
Blinking method:
Thread splashThread2;
private void BlinkMode(View view){
splashThread2 = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
if(!isOn[0]){
OnFlash();
isOn[0] = true;
} else {
isOn[0] = false;
OffFlash();
}
}
} catch (Exception e) {
}
}
};
splashThread2.start();
}
Handle when goback
#Override
public void onStop() {
super.onStop();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
#Override
public void onPause() {
super.onPause();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
On/Off Method for new version of Android:
private void OnFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
isOn[0] = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
private void OffFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, false); //Turn ON
isOn[0] = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}

How to make flash light blink while pressing a button

I am fairly new to android and I am trying to make flash light blink when the button is pressed. The code i am using is for simply switching on and off the flashlight. I am trying to add another button which will make the flashlight blink in a certain pattern. Is it possible that we set the pattern parameters just like we do in vibrating in a pattern
My code is as below:
public class MainActivity extends Activity {
private InterstitialAd interstitial;
private Camera camera;
ImageButton flashLightSwitchImage;
private boolean isFlashlightOn;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashLightSwitchImage = (ImageButton) findViewById(R.id.flashlight_switch);
boolean isCameraFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isCameraFlash) {
showCameraAlert();
} else {
camera = Camera.open();
params = camera.getParameters();
}
flashLightSwitchImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (isFlashlightOn) {
setFlashLightOff();
} else {
setFlashLightOn();
}
}
});
}
private void showCameraAlert() {
new AlertDialog.Builder(this)
.setTitle("Error loadin Flash!")
.setMessage("Flash Not Available in this Device")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
finish();
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}}}}
This code right here is working fine but it simply switches on and off the flashlight.
I want to introduce another button which makes the flash light blink in a pattern.
Try this code for blinking the flash. You can edit this to support your required pattern
String myString = "01010101010101";
long blinkDelay 50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
} try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
} }
use this code on the listener of your button
getCamera();
Toast.makeText(context, "Ringing", Toast.LENGTH_SHORT).show();
String myString = "01010101010010101010101";
long blinkDelay =500;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
//params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
turnOnFlash();
} else {
// params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
turnOffFlash();
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
and define this code outside on create method
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
// Log.d("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
// playSound();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
// toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
//playSound();
params = camera.getParameters();
params.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
// toggleButtonImage();
}}

Android :camera ui disapering on camera starts but the preview remains

This is the main activity where the XML file is launched: VideoCaptureActivity.java:
public class VideoCaptureActivity extends Activity
{
private static final String TAG = "VideoCaptureActivity";
Camera camera;
ImageButton recordButton;
ImageButton stopButton;enter code here
ImageButton back;
Button flash;
Button flashoff;
Button flip;
SeekBar sb;
FrameLayout cameraPreviewFrame;
CameraPreview cameraPreview;
MediaRecorder mediaRecorder;
private Spinner spinner1;
private Timer myTimer;
File file;
int currentZoomLevel = 0;
int maxZoomLevel = 0;
int MAX_ZOOM=15;
int fcamera =0;
Size temp;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
super.setContentView(R.layout.video_capture);
// this.mediaRecorder = new MediaRecorder();
// this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
// this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
this.cameraPreviewFrame = (FrameLayout)super.findViewById(R.id.camera_preview);
this.recordButton = (ImageButton)super.findViewById(R.id.recordButton);
this.stopButton = (ImageButton)super.findViewById(R.id.stopButton);
spinner1 = (Spinner) findViewById(R.id.spinner1);
back =(ImageButton)findViewById(R.id.back);
this.flash=(Button)findViewById(R.id.flashon);
this.flashoff=(Button)findViewById(R.id.fashoff);
this.sb = (SeekBar) findViewById(R.id.seekBar1);
this.sb.setOnSeekBarChangeListener( new seekListener() );
this.toggleButtons(false);
// we'll enable this button once the camera is ready
this.recordButton.setEnabled(false);
// this.flash.setEnabled(false);
stopButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopRecording(v);
}
});
flash.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flashLightOn(v );
}
});
flashoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flashLightOff(v );
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
Intent intent = new Intent(VideoCaptureActivity.this ,MainGrid.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
void toggleButtons(boolean recording) {
this.recordButton.setEnabled(!recording);
this.recordButton.setVisibility(recording ? View.GONE : View.VISIBLE);
this.stopButton.setEnabled(recording);
this.stopButton.setVisibility(recording ? View.VISIBLE : View.GONE);
}
public void flashLightOn(View view) {
// this.flash.setVisibility(View.INVISIBLE);
this.flash.setVisibility(View.INVISIBLE);
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
// camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
// camera.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOn()",
Toast.LENGTH_SHORT).show();
}
}
public void flashLightOff(View view) {
// this.flash.setVisibility(View.VISIBLE);
this.flash.setVisibility(View.VISIBLE);
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOff",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
// initialize the camera in background, as this may take a while
// try {
// Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
// sb.setMax(camera.getParameters().getMaxZoom());
// sb.setProgress(0);
// // Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
//
// } catch (RuntimeException e) {
// Log.wtf(TAG, "Failed to get camera", e);
// }
// if (camera == null) {
// Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
// Toast.LENGTH_SHORT).show();
// } else {
// VideoCaptureActivity.this.initCamera(camera);
// }
new AsyncTask<Void, Void, Camera>() {
#Override
protected Camera doInBackground(Void... params) {
try {
Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
sb.setMax(camera.getParameters().getMaxZoom());
sb.setProgress(0);
// Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
return camera == null ? Camera.open(0) : camera;
} catch (RuntimeException e) {
Log.wtf(TAG, "Failed to get camera", e);
return null;
}
}
#Override
protected void onPostExecute(Camera camera) {
if (camera == null) {
Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
Toast.LENGTH_SHORT).show();
} else {
initCamera(camera);
}
}
}.execute();
}
void initCamera(Camera camera) {
// we now have the camera
Camera.Parameters params = camera.getParameters();
List<Size> previewSize = params.getSupportedPreviewSizes();
temp = previewSize.get(0);
// for (int i =0; i<previewSize.size(); i++)
// {
//
// }
this.camera = camera;
// create a preview for our camera
this.cameraPreview = new CameraPreview( VideoCaptureActivity.this,camera);
// add the preview to our preview frame
this.cameraPreviewFrame.addView(this.cameraPreview);
// enable just the record button
this.recordButton.setEnabled(true);
}
void releaseCamera() {
if (this.camera != null) {
// this.camera.lock(); // unnecessary in API >= 14
// //this.camera.stopPreview();
this.camera.release();
this.camera = null;
this.cameraPreviewFrame.removeView(this.cameraPreview);
}
}
void releaseMediaRecorder() {
if (this.mediaRecorder != null) {
this.mediaRecorder.reset(); // clear configuration (optional here)
this.mediaRecorder.release();
this.mediaRecorder = null;
}
}
void releaseResources() {
this.releaseMediaRecorder();
this.releaseCamera();
}
#Override
public void onPause() {
super.onPause();
this.releaseResources();
}
#Override
public void onStop()
{
super.onStop();
this.releaseCamera();
}
#Override
public void onDestroy()
{
super.onDestroy();
this.releaseCamera();
}
// gets called by the button press
public void startRecording(final View v) {
Log.d(TAG, "startRecording()");
// we need to unlock the camera so that mediaRecorder can use it\\
// this.camera.unlock(); // unnecessary in API >= 14
// now we can initialize the media recorder and set it up with our
// camera
this.camera.stopPreview();
this.camera.release();
this.mediaRecorder = new MediaRecorder();
// this.mediaRecorder.setCamera(this.camera);
this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
//// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
this.mediaRecorder.setProfile(CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_BACK,
CamcorderProfile.QUALITY_HIGH));
// this.mediaRecorder.setVideoSize(320, 240);
// this.mediaRecorder.setVideoFrameRate(15);
// this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_1080P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
// else
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_720P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
// else
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
this.mediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
this.mediaRecorder.setPreviewDisplay(this.cameraPreview.getHolder().getSurface());
// mediaRecorder.setMaxDuration((int) 1800);
try {
//this.toggleButtons(true);
String sec=String.valueOf(spinner1.getSelectedItem()) ;
//int seconds =Integer.parseInt(sec);
String toast =String.valueOf(spinner1.getSelectedItem()) +" Recording";
Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
if(sec.equals("1")){
this.recordButton.setVisibility(View.INVISIBLE);
this.mediaRecorder.setMaxDuration(1000);
this.mediaRecorder.prepare();
// start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// this.recordButton.setVisibility(View.VISIBLE);
this.recordButton.setVisibility(View.VISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopRecording(v);
}
},1000);
}
else if(sec.equals("2")){
this.recordButton.setVisibility(View.INVISIBLE);
this.mediaRecorder.setMaxDuration(2000);
this.mediaRecorder.prepare();
// start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// this.recordButton.setVisibility(View.VISIBLE);
this.recordButton.setVisibility(View.VISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopRecording(v);
}
},2000);
}
else{
//this.mediaRecorder.setMaxDuration(5000);
this.toggleButtons(true);
this.mediaRecorder.prepare();
//start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// stopRecording(v);
// enable the stop button by indicating that we are recording
}
} catch (Exception e) {
Log.wtf(TAG, "Failed to prepare MediaRecorder", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
this.releaseResources();
}
}
// gets called by the button press
public void stopRecording(View v) {
Log.d(TAG, "stopRecording()");
assert this.mediaRecorder != null;
try {
this.mediaRecorder.stop();
Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
// we are no longer recording
this.toggleButtons(false);
} catch (RuntimeException e) {
// the recording did not succeed
Log.w(TAG, "Failed to record", e);
if (this.file != null && this.file.exists() && this.file.delete()) {
Log.d(TAG, "Deleted " + this.file.getAbsolutePath());
}
return;
} finally {
this.releaseMediaRecorder();
}
if (this.file == null || !this.file.exists()) {
Log.w(TAG, "File does not exist after stop: " + this.file.getAbsolutePath());
} else {
Log.d(TAG, "Going to display the video: " + this.file.getAbsolutePath());
Intent intent = new Intent(this, VideoPlaybackActivity.class);
intent.setData(Uri.fromFile(file));
super.startActivity(intent);
}
}
private File initFile() {
File dir = new File(
Environment.getExternalStorageDirectory().toString() +
Utils.OUR_TEMP_FOLDER);
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG, "Failed to create storage directory: " + dir.getAbsolutePath());
Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record, Toast.LENGTH_SHORT).show();
this.file = null;
} else {
this.file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return this.file;
}
private class seekListener implements SeekBar.OnSeekBarChangeListener
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser == true)
{
Parameters p = camera.getParameters();
p.setZoom(progress);
camera.setParameters(p);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
}
My camera prewiew is as follows
CameraPreview.java:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private final Camera camera;
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
Camera.Parameters params = camera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
else
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO))
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
this.camera = camera;
super.getHolder().addCallback(this);
// required for API <= 11
super.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated()");
// now that we have the surface, we can start the preview
try {
this.camera.setPreviewDisplay(holder);
this.camera.startPreview();
} catch (IOException e) {
Log.wtf(TAG, "Failed to start camera preview", e);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// we will release the camera preview in our activity before this
// happens
Log.d(TAG, "surfaceDestroyed()");
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// our activity runs with screenOrientation="landscape" so we don't
// care about surface changes
Parameters params = camera.getParameters();
Log.d(TAG, "surfaceChanged()");
}
}
I dont know what went wrong camera is working fine but the UI is visible at start but invisible after some time but the preview remains and if ii clicked on to the button which is invisible it works .so the control works but cant see.

Where in the code set camera parameters?

I'm using this to use android camera:
public class Login extends Activity implements SurfaceHolder.Callback {
public int idCamera(int id) {
if (id == 0) { id = 1; } else { id = 0; }
int tcam = Camera.getNumberOfCameras();
if (tcam == 1) { id = 0; }
return id;
}
public class idCameraV {
public int id;
}
public static class camHolder {
public static SurfaceHolder id;
}
private Camera camera;
private SurfaceView surfaceView;
static String senha2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final idCameraV idCam = new idCameraV();
idCam.id = 0;
camera = Camera.open(idCam.id);
Camera.Parameters parametro = camera.getParameters(); // WORKS OK
parametro.setFlashMode("on"); // WORKS OK
camera.setParameters(parametro); // WORKS OK
surfaceView = (SurfaceView) findViewById(R.id.preview);
surfaceView.getHolder().addCallback(this);
final ImageButton button1 = (ImageButton) findViewById(R.id.bt_camera);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
camera.stopPreview();
camera.release();
idCam.id = idCamera(idCam.id);
camera = Camera.open(idCam.id);
Camera.Parameters parametro = camera.getParameters();
parametro.setFlashMode("on"); // THIS LINE AND ABOVE WORKS. I CAN READ BY GETFLASHMODE
camera.setParameters(parametro); // ERROR IN HERE
camera.startPreview();
try {
camera.setPreviewDisplay(camHolder.id);
} catch (IOException e) {
e.printStackTrace();
}
}
});
final ImageButton button2 = (ImageButton) findViewById(R.id.bt_login);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText senha = (EditText)findViewById(R.id.senha);
senha2 = senha.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
RelativeLayout aviso = (RelativeLayout) findViewById(R.id.aguarde);
aviso.setVisibility(View.VISIBLE);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String coordenadas = GPS.coordenadas(locationManager);
String android_id = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
camera.takePicture(null, null, new TiraFoto(getApplicationContext(), android_id, coordenadas, aviso, connMgr, "LOGIN_", camera));
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (camera != null) { camera.release(); }
}
#Override
protected void onPause() {
super.onPause();
if (camera != null) { camera.stopPreview(); }
}
#SuppressWarnings("static-access")
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
final camHolder camHolderId = new camHolder();
camHolderId.id = holder;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (holder.getSurface() != null) {
try {
camera.stopPreview();
} catch (Exception e) {
}
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
}
It works ok, but when I do the camera swap, the app freezes. I'm setting the flashmode when I open the camera first time, and it works, but when I do the swap, I get a set parameter error. Where I must set this parameters?
The front camera doesn't support flash mode, maybe the code as below can work
if(idCam.id == 0)
parametro.setFlashMode("on");
According to your question, please refer to the Android Developers: Camera
Basically, you'll need to set the camera parameters inside surfacedChanged method
And here for your information, I copy/paste the related code:
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
Please let me know if it works

why camera is not working properly?

I am using camera in my application,I have no done more work on camera my requirement is only taken picture and with front and back camera and flash light.Camera will be open inside a customview for that I am using this code:-
public class CaptureDealImage extends Activity implements OnClickListener,
CameraCallback {
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
private Button objbtncapture, objbtnback, objbtngalary, objbtnretake,
objbtnuse;
private Button objbtnflashlight, objbbtnfrontcam;// ,flashButton_p,flashButton_l,cameraRotate_p,cameraRotate_l;
private boolean recording;
private TextView show_p, show_l;
int nCurrentOrientation;
private WakeLock wakeLock;
private int count, mode;
private boolean backendCamera = true;
private FrameLayout mymiddlelayout;
private String sdcardpath;
private boolean flashlight = false;
private boolean cameramode = false;
private boolean isfrontcamera = false;
private RelativeLayout objrelativeLayoutretake, objrelativeLayout3;
private byte[] data;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dealpick);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = mgr
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
// Get Camera for preview
objbtnflashlight = (Button) findViewById(R.id.btnflashlight);
objbbtnfrontcam = (Button) findViewById(R.id.bbtnfrontcam);
objbtncapture = (Button) findViewById(R.id.btncapture);
objbtngalary = (Button) findViewById(R.id.btngalary);
objbtnback = (Button) findViewById(R.id.btnback);
objbtnretake = (Button) findViewById(R.id.btnretake);
objbtnuse = (Button) findViewById(R.id.btnuse);
objrelativeLayoutretake = (RelativeLayout) findViewById(R.id.relativeLayoutretake);
objrelativeLayout3 = (RelativeLayout) findViewById(R.id.relativeLayout3);
objbtnback.setOnClickListener(this);
objbtncapture.setOnClickListener(this);
objbtngalary.setOnClickListener(this);
objbtnflashlight.setOnClickListener(this);
objbbtnfrontcam.setOnClickListener(this);
objbtnretake.setOnClickListener(this);
objbtnuse.setOnClickListener(this);
}
private Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
Display getOrient = getWindowManager().getDefaultDisplay();
if (getOrient.getHeight() > getOrient.getWidth()) {
c.setDisplayOrientation(90);
}
} catch (Exception e) {
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
myCamera = getCameraInstance();
if (myCamera == null) {
Toast.makeText(CaptureDealImage.this, "Fail to get Camera",
Toast.LENGTH_LONG).show();
}
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
mymiddlelayout = (FrameLayout) findViewById(R.id.middlelayout);
mymiddlelayout.removeAllViews();
mymiddlelayout.addView(myCameraSurfaceView);
myCameraSurfaceView.setCallback(this);
}
private void releaseCamera() {
/*
* if (myCamera != null) { myCamera.release(); // release the camera for
* other applications myCamera = null; }
*/
Camera camera = this.myCameraSurfaceView.getCamera();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
wakeLock.release();
/*
* ReleaseRootBitmap mReleaseRootBitmap=new ReleaseRootBitmap();
* LinearLayout
* mLinearLayout=(LinearLayout)findViewById(R.id.record_video_parent);
* mReleaseRootBitmap.unbindDrawables(mLinearLayout);
*/
}
public class MyCameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private CameraCallback callback = null;
private boolean isStarted = true;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
initialize(context);
}
public MyCameraSurfaceView(Context context) {
super(context);
initialize(context);
}
public void setCallback(CameraCallback callback) {
this.callback = callback;
}
public void startPreview() {
mCamera.startPreview();
}
public void initialize(Context mcontext) {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int weight, int height) {
if (holder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
if (null != mCamera) {
mCamera.stopPreview();
}
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
if (null != mCamera) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
/*
* if (null != camera) { camera.startPreview();
*/
} catch (Exception e) {
Log.d("check",
"Error starting camera preview: " + e.getMessage());
}
}
public Camera getCamera() {
return this.mCamera;
}
public void startTakePicture() {
mCamera.autoFocus(new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
takePicture();
}
});
}
public void takePicture() {
mCamera.takePicture(new ShutterCallback() {
#Override
public void onShutter() {
if (null != callback)
callback.onShutter();
}
}, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (null != callback)
callback.onRawPictureTaken(data, camera);
}
}, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (null != callback)
callback.onJpegPictureTaken(data, camera);
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// mCamera.startPreview();
try {
mCamera.setPreviewDisplay(holder);
} catch (Throwable ignored) {
}
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (null != callback)
callback.onPreviewFrame(data, camera);
}
});
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
// camera.stopPreview();
mCamera.release();
mCamera = null;
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Display display = getWindowManager().getDefaultDisplay();
if (display.getHeight() > display.getWidth()) {
myCamera.setDisplayOrientation(90);
show_l.setVisibility(View.GONE);
show_p.setVisibility(View.VISIBLE);
} else {
myCamera.setDisplayOrientation(0);
show_l.setVisibility(View.VISIBLE);
show_p.setVisibility(View.GONE);
}
}
private Handler checkHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (recording && count <= 15) {
if (mode == 1) {
show_l.setText(count + "/15");
} else {
show_p.setText(count + "/15");
}
}
}
};
#Override
public void onClick(View v) {
if (v.equals(objbtncapture)) {
myCameraSurfaceView.startTakePicture();
}
if (v.equals(objbtngalary)) {
// releaseCamera();
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
final int ACTIVITY_SELECT_IMAGE = 100;
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
}
if (v.equals(objbtnflashlight)) {
if (!isfrontcamera) {
if (!flashlight) {
flashlight = true;
Parameters params = myCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
myCamera.setParameters(params);
} else {
flashlight = false;
Parameters params = myCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(params);
}
}
}
if (v.equals(objbbtnfrontcam)) {
if (!cameramode) {
cameramode = true;
switchToCamera(cameramode);
} else {
cameramode = false;
switchToCamera(cameramode);
}
}
if (v.equals(objbtnback)) {
finish();
}
if (v.equals(objbtnretake)) {
objrelativeLayoutretake.setVisibility(View.GONE);
objrelativeLayout3.setVisibility(View.VISIBLE);
myCameraSurfaceView.startPreview();
}
if (v.equals(objbtnuse)) {
try {
PhotoComplete(data);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void switchToCamera(boolean frontcamera) {
releaseCamera();
if (frontcamera) {
isfrontcamera = true;
myCamera = getFrontCameraId();
} else {
isfrontcamera = false;
myCamera = getCameraInstance();
}
if (myCamera == null) {
Toast.makeText(CaptureDealImage.this, "fail to get front camera",
Toast.LENGTH_SHORT).show();
myCamera = getCameraInstance();
}
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
mymiddlelayout = (FrameLayout) findViewById(R.id.middlelayout);
mymiddlelayout.removeAllViews();
mymiddlelayout.addView(myCameraSurfaceView);
}
Camera getFrontCameraId() {
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
Camera camera = null;
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
camera = Camera.open(camIdx);
Display getOrient = getWindowManager().getDefaultDisplay();
if (getOrient.getHeight() > getOrient.getWidth()) {
camera.setDisplayOrientation(90);
}
// myCamera.unlock();
// mediaRecorder.setCamera(myCamera);
// myCamera.setParameters(myCamera.getParameters());
} catch (RuntimeException e) {
Log.e("",
"Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return camera;
// No front-facing camera found
}
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
#Override
public void onShutter() {
// TODO Auto-generated method stub
}
#Override
public void onRawPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
#Override
public void onJpegPictureTaken(byte[] data, Camera camera) {
try {
this.data = data;
objrelativeLayoutretake.setVisibility(View.VISIBLE);
objrelativeLayout3.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
private void PhotoComplete(byte[] data) throws FileNotFoundException,
IOException {
try {
sdcardpath = String.format(getResources().getString(R.string.path),
System.currentTimeMillis());
FileOutputStream outStream = new FileOutputStream(sdcardpath);
outStream.write(data);
outStream.close();
Bundle objbundle = new Bundle();
Intent objintent = new Intent(CaptureDealImage.this,
com.flashdeal.mycamera.SetDealImageCategory.class);
objbundle.putString("from", "camera");
objbundle.putString("imagepath", sdcardpath);
Log.e("check===path", sdcardpath);
objintent.putExtras(objbundle);
startActivity(objintent);
finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public String onGetVideoFilename() {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bundle objbundle = new Bundle();
Intent objintent = new Intent(CaptureDealImage.this,
com.flashdeal.mycamera.SetDealImageCategory.class);
objbundle.putString("from", "camera");
objbundle.putString("imagepath", filePath);
objintent.putExtras(objbundle);
startActivity(objintent);
finish();
}
}
}
But this not work and when I click front camera ,again back camera and again on capture button camera become freez.Please anyone guide me or give imp link for my requirement.
Refer this links ::
They are facing the same issue that you have.Have a look at once .
Link 1
Link 2
Hope this helps :)

Categories

Resources