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();
}}
Related
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();
}
}
}
I am facing a problem in a custom camera application. With the flash function turned ON, the phone takes the 1st photo with flash, but on the 2nd photo it doesn't use the flash.
flashCameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPressed) {
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.onflash));
flashOnButton();
} else if (isPressed) {
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.offflash));
isPressed = !isPressed;
flashOffButton();
} else
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.onflash));
flashOnButton();
}
});
private void flashOnButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_ON
: Camera.Parameters.FLASH_MODE_ON);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
private void flashOffButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_OFF
: Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
Take a look at the code below. You can do something similar to it:
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
//change the picture
turnOffFlash();
} else {
// turn on flash
//change the picture
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
What we are doing here is checking if the Flash is ON or OFF, if it is ON, we call the method turnOffFlash() to turn it off and if it is OFF we call the method turnOnFlash() to turn it on.
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);
}
}
});
}
}
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.
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