I am trying to implement flashligth in my app. As it is part of a bigger program i created another activity i.e, flash_activity.java and intent it from another fragment Tab3. But unfortunately on clicking the button in flash_activity which is meant to make the flashlight on is not responding. Here is my code for Tab3 ,flash_activity. Please help me.
package com.example.bavarian.sos;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.content.Intent;
public class Tab3 extends Fragment {
ImageButton imageButton;
private boolean playing = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3, container, false);
imageButton = (ImageButton) rootView.findViewById(R.id.torch);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Flash_activity.class);
startActivity(intent);
}
});
return rootView;
}
}
My Flash_activity.java is :
package com.example.bavarian.sos;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Flash_activity extends AppCompatActivity {
// private ImageButton btnSwitch;
Button button;
Camera camera;
boolean isFlashOn;
boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_activity);
//btnSwitch= (ImageButton) findViewById(R.id.torch1);
button = (Button) findViewById(R.id.button);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(Flash_activity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE,
"OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
// toggleButtonImage();
// Switch button click event to toggle flash on/off
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Error. Failed to Open", 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(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
// toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(Flash_activity.this, R.raw.alrm);
} else {
mp = MediaPlayer.create(Flash_activity.this, R.raw.alrm);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/* private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.flash_on);
}else{
btnSwitch.setImageResource(R.drawable.flash_off);
}
}
*/
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOnFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if (hasFlash)
turnOffFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
What i am missing...please help
Related
I have developed an android app that records users voice. Its a learning app for me. However the problem is that the record button works only once and the second time when I hit record it does not stop at all. There are total four buttons Record-Stop record. Play-stop play.
The exact problem is that when second time record is pressed the stop button stays greyed out.
The third time I press record the application crashes directly.
package com.example.soundrecorder;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
Button btnRecord, btnStopRecord, btnPlay, btnStop;
String pathsave="";
MediaRecorder mediaRecorder;
MediaPlayer mediaplayer;
final int REQUEST_PERMISSION_CODE=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Request Runtime Permission
if(!CheckPermissionFromDevice())
requestPermissions();
//init view
btnPlay = (Button)findViewById(R.id.btnPlay);
btnRecord = (Button)findViewById(R.id.btnStartRecord);
btnStop = (Button)findViewById(R.id.btnStop);
btnStopRecord = (Button)findViewById(R.id.btnStopRecord);
btnRecord.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(CheckPermissionFromDevice())
{
pathsave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"
+ UUID.randomUUID().toString()+"_audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
}catch (IOException e){
e.printStackTrace();
}
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording...", Toast.LENGTH_SHORT).show();
}
else
{
requestPermissions();
}
}
});
btnStopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
btnStopRecord.setEnabled(false);
btnPlay.setEnabled(true);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStop.setEnabled(true);
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(false);
mediaplayer = new MediaPlayer();
try{
mediaplayer.setDataSource(pathsave);
mediaplayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaplayer.start();
Toast.makeText(MainActivity.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
btnPlay.setEnabled(true);
if(mediaplayer !=null)
{
mediaplayer.stop();
mediaplayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathsave);
}
private void requestPermissions()
{
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,
},REQUEST_PERMISSION_CODE );
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case REQUEST_PERMISSION_CODE:
{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
else
{
Toast.makeText(this,"Permission Denied",Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private boolean CheckPermissionFromDevice()
{
int write_external_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int record_audio_result = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
return write_external_storage_result == PackageManager.PERMISSION_GRANTED && record_audio_result == PackageManager.PERMISSION_GRANTED;
}
}
There doesn't seem to be a btnStopRecord.setEnabled(true); in the btnRecord click function. If you can stop the first recording, it's probably because the stop record button is enabled by default, but when you press it, it disables itself. You should probably initialize the enabled state of your buttons too, but this should solve your problem:
public void onClick(View view) {
if(CheckPermissionFromDevice())
pathsave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"_audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
btnStopRecord.setEnabled(true); //enable stop record
btnPlay.setEnabled(false); //shouldn't be able to play while recording too
btnRecord.setEnabled(false); //yours to see if should be able to restart record while recording, but probably not if it crashes
btnStop.setEnabled(false); //probably should be disabled too on record
//...rest of the function
I have flashlight apk with two problem.
İf I use camera, camera.params. My apk working with lower versions Android 5. THen if I use camera2 and camera.manager, My app working with Android 5 and higger versions.
I wanna work with Android version 4 and higger, work with all versions.
How can I do this?
Pls help me for this, thanks.
package com.hallac.erdogan.spechflash;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton btnSwitch;
ImageButton flashlight;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
private CameraManager mCameraManager;
private String mCameraId;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//full keran ile ilgili ayarlar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,//full keran ile ilgili ayarlar
WindowManager.LayoutParams.FLAG_FULLSCREEN);//full keran ile ilgili ayarlar
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.buton);
flashlight=(ImageButton)findViewById(R.id.flashlight);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
flashlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(getBaseContext(),SpeakNow.class);
startActivity(intent);
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
}
}
}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
}
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.light_on);
}else{
btnSwitch.setImageResource(R.drawable.light_off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
// turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
if (camera != null) {
camera.release();
camera = null;
}
Log.d("Camera","Back Pressed");
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
// if (camera != null) {
// camera.release();
// camera = null;
// }
}
}
I am trying to implement flashligth in my app. As it is part of a bigger program i created another activity i.e, flash_activity.java and intent it from another fragment Tab3. But unfortunately on clicking the button
in flash_activity which is meant to make the flashlight on is not responding.
Here is my code for Tab3 ,flash_activity. Please help me.
Tab3
package com.example.bavarian.sos;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.content.Intent;
//Our class extending fragment
public class Tab3 extends Fragment
{
ImageButton imageButton;
private boolean playing = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3, container, false);
imageButton = (ImageButton) rootView.findViewById(R.id.torch);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Flash_activity.class);
startActivity(intent);
}
});
return rootView;
}
}
flash_activity
package com.example.bavarian.sos;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Flash_activity extends AppCompatActivity {
// private ImageButton btnSwitch;
Button button;
Camera camera;
boolean isFlashOn;
boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_activity);
//btnSwitch= (ImageButton) findViewById(R.id.torch1);
button = (Button) findViewById(R.id.button);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(Flash_activity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE,
"OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
// toggleButtonImage();
// Switch button click event to toggle flash on/off
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Error. Failed to Open", 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(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
// toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(Flash_activity.this, R.raw.alrm);
} else {
mp = MediaPlayer.create(Flash_activity.this, R.raw.alrm);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/* private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.flash_on);
}else{
btnSwitch.setImageResource(R.drawable.flash_off);
}
}
*/
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOnFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if (hasFlash)
turnOffFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
I tried to use an onTouch and OnClicklistener to turn the light on and off. It turns on the light, but doesn't turn it off again. I don't know what I'm doing wrong, because it turns on.
Here is my code:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public Camera camera;
private Camera.Parameters params;
ImageButton flashlightSwitchImg;
private boolean isFlashlightOn;
private boolean isFlashLightOff;
TextView textViewbutton;
private boolean hasCam;
private SurfaceHolder mHolder;
public boolean hasFlash() {
if (camera == null) {
return false;
}
Camera.Parameters parameters = camera.getParameters();
if (parameters.getFlashMode() == null) {
return false;
}
List<String> supportedFlashModes = parameters.getSupportedFlashModes();
if (supportedFlashModes == null || supportedFlashModes.isEmpty() || supportedFlashModes.size() == 1 && supportedFlashModes.get(0).equals(Camera.Parameters.FLASH_MODE_OFF)) {
return false;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashlightSwitchImg = (ImageButton) findViewById(R.id.imageButton);
textViewbutton = (TextView) findViewById(R.id.textView2);
try {
//Log.d("TORCH", "Check cam");
// Get CAM reference
camera = Camera.open();
params = camera.getParameters();
camera.startPreview();
hasCam = true;
//Log.d("TORCH", "HAS CAM ["+hasCam+"]");
} catch (Throwable t) {
t.printStackTrace();
}
if (hasFlash()) {
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("Flashlight not available...");
// Setting Dialog Message
alertDialog.setMessage("Your device is not compatible with this app or doesn't have a flashlight. DO YOU WANT TO USE YOUR SCREEN AS A TORCH INSTEAD?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Yes, of course", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
FrameLayout legacy = (FrameLayout) findViewById(R.id.legacy);
// Write your code here to invoke YES event
legacy.setVisibility(View.VISIBLE);
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("No, thanks", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
flashlightSwitchImg.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isFlashlightOn) {
turnOff();
} else {
turnOn();
}
return false;
}
});
}
public void turnOn() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
textViewbutton.setText(R.string.light_turn_off);
}
public void turnOff() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
textViewbutton.setText(R.string.lo);
}
}
picking at the little things looks as thought you never change the value of "isFlashlightOn" or "isFlashlightOff". you are using "isFlashlightOn" in you if statement.
flashlightSwitchImg.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isFlashlightOn) {
turnOff();
} else {
turnOn();
}
return false;
}
});
So i recomend removing "isFlashlightOff", and changing the "IsFlashlightOn" Value here.
public void turnOn() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
textViewbutton.setText(R.string.light_turn_off);
}
public void turnOff() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
textViewbutton.setText(R.string.lo);
}
like so:
public void turnOn() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashlightOn = True;
textViewbutton.setText(R.string.light_turn_off);
}
public void turnOff() {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashlightOn = False;
textViewbutton.setText(R.string.lo);
}
By the way. it still runs without crashing but only turns on because the value defaults to false.
I have a problem in flash led. When I turn on flash after 2 seconds flash led off automatically. I don't know why it's behaving like that. Can anyone have any idea please help me.
public void cameraFlashOn() {
try {
camera = Camera.open();
Parameters params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(params);
camera.startPreview();
camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for off the flash i used following code
public void cameraFlashOff() {
try {
camera.stopPreview();
camera.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
package com.mkyong.android;
import android.app.Activity;
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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FlashLightActivity extends Activity {
//flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private Button button;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
});
}
}