How can I keep the flashlight on in the background even when I switch to next activity or next application. Also my flashlight turns off automatically when I my screen locks and I want to keep my flash glowing even the screen locks.
This is my current code:
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedform);
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// First check if device is supporting flashlight or not
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(SavedForm.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
// 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();
}
}
});
}
// 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(SavedForm.this, R.raw.flashoff);
}else{
mp = MediaPlayer.create(SavedForm.this, R.raw.flashon);
}
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.button_on);
}else{
btnSwitch.setImageResource(R.drawable.button_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;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_savedform, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id==android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
The best way to do is by Running a Background service that handles the Flashlight.
You need to put your FlashLight Start and Stop code inside the OnStart and onDestroy of the Service. That you need to do on your own
First of all create a class named FlashLightService that extends the Service
public class FlashLightService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
// Put Your Code To Start the FlashLight Over Here
}
#Override
public void onDestroy() {
// Put Your Code To Stop the FlashLight Over Here
}
Now from any Activity you can start and stop the Flashlight according to your need
To start The FlashLight
startService(new Intent(this, FlashLightService.class));
To stop the FlashLight
stopService(new Intent(this, FlashLightService.class));
Do not forget to mention this in your AndroidManifest.xml
Let me know if this works! :)
Remove these code or line.
`
#Override
protected void onStop() {
super.onStop();
// on stop release the camera`enter code here`
if (camera != null) {
camera.release();
camera = null;
}
`
It worked for me.
I am not an android expert but I would recommend,
run it as service or run it as singleton thread.
The flash depends on the camera. Your onStop method contains: camera.release() which will release the camera hardware overriding any other acquisition methods implemented.
You could use background service to control the camera hardware. Start it from an activity and stop the service when your app is closed.
Related
i have this code, and i want to do appear an insterstitial ad when the flash is off (my app is a flashlight) But when i try to do it i get an error.
All what i do is to put the onReceiveAd code where i want it.
I put the code here:
// 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(); <---- FLASH GO OFF
#Override
public void onReceiveAd(Ad ad) { <------ Insterstitial AD should APPEAR
Log.d("OK", "Received ad");
if (ad == interstitial) {
interstitial.show();
}
}
} else{
etc etc...
But i get this error:
Multiple markers at this line
- Syntax error on token "(", ;
expected
- Syntax error on token ")", ;
expected
How can i do to do it works?
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the interstitial
interstitial = new InterstitialAd(this, "My id here");
// Create ad request
AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
// Set Ad Listener to use the callbacks below
interstitial.setAdListener(this);
Toast.makeText(MainActivity.this, "Touch amumu's body to play a sound!", Toast.LENGTH_SHORT).show();
// flash switch button
btnSwitch = (ImageView) findViewById(R.id.imageView1);
// First check if device is supporting flashlight or not
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(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ImageView Facebook = (ImageView) findViewById(R.id.imageView3);
Facebook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mp = MediaPlayer.create(MainActivity.this, R.raw.draven);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
Intent facebookIntent = new Intent(Intent.ACTION_SEND);
facebookIntent.setType("text/plain");
facebookIntent.setPackage("com.facebook.katana");
facebookIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=lol.flashlight");
startActivity(facebookIntent);
}});
ImageView Twitter = (ImageView) findViewById(R.id.imageView4);
Twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.draven);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
//al apretar click en el boton Ir a Web abre el browser con la pág: google.com
Intent browserIntent =
new Intent(Intent.ACTION_VIEW,
Uri.parse("https://twitter.com/intent/tweet?text=https://play.google.com/store/apps/details?id=lol.flashlight%20-%20This%20app%20is%20amazing,%20i%20love%20it!"));
startActivity(browserIntent);
}});
//OnClick del View :D
ImageView Ez = (ImageView) findViewById(R.id.imageView2);
Ez.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.amumu);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}});
// 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();
}
}
});
}
// 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;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(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(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(MainActivity.this, R.raw.playbutton);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.rayo);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.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();
}
#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;
}
}
#Override
public void onReceiveAd(Ad ad) {
Log.d("OK", "Received ad");
if (ad == interstitial) {
interstitial.show();
}
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
}
my app uses the camera flash but I do not understand why if I open another app and then resume my app the app crashes. I think because I have not inserted the pause and resume in the app.
This is MainActivity:
public class MainActivity extends ActionBarActivity {
//flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private Button button;
private LinearLayout rl;
int i=0;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonFlashlight);
rl=(LinearLayout) findViewById(R.id.container);
rl.setBackgroundColor(getResources().getColor(R.color.Black));
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;
button.setBackgroundResource(R.drawable.off);
rl.setBackgroundColor(getResources().getColor(R.color.Black));
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
button.setBackgroundResource(R.drawable.on);
rl.setBackgroundResource(R.drawable.check);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
03-29 21:24:51.048: D/AndroidRuntime(27113): Shutting down VM
03-29 21:24:51.048: W/dalvikvm(27113): threadid=1: thread exiting with uncaught exception (group=0x418eeda0)
03-29 21:24:51.058: E/AndroidRuntime(27113): FATAL EXCEPTION: main
03-29 21:24:51.058: E/AndroidRuntime(27113): Process: com.example.torcia, PID: 27113
03-29 21:24:51.058: E/AndroidRuntime(27113): java.lang.RuntimeException: Method called after release()
When you let your app go into the background, stop() is called. Then you release your camera. After this you cannot use it again- you need to call camera.open() and get a new camera object. I suggest not creating camera objects in onCreate, but only doing it in onStart (or onResume).
The problem is that you release the camera when the application is stopped, but you don't initialise the camera again when the application is resumed. Your camera initialisation code is in onCreate which won't get called again.
It's probably best to initialise the camera in onResume and release it in onPause.
E.g.
#Override
protected void onResume() {
super.onResume();
camera = Camera.open();
}
#Override
protected void onPause() {
super.onPause();
if (camera != null) {
camera.release();
}
}
*Hi, i have a flashlight app, but i can´t run it, idk why, i think that is the OnClickListener in Background.. maybe its wrong, or idk, i am newbie , sorry D:
Logcat: enter link description here (Nothing important i think)
I have other FlashLight and the Background OnClickListener is the difference between these apps.. But.. How can i put, that when i click The LAYOUT or BACKGROUND ( the same thing ) turn on flash ? :|
Here the code:*
public class MainActivity extends Activity {
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to Exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
finish();
//close();
}
})
.setNeutralButton("Rate us!", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
{
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Couldn´t launch Google Play",
Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// First check if device is supporting flashlight or not
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(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(AlertDialog.BUTTON_POSITIVE,"OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Intent Screen = new Intent (MainActivity.this, ScreenActivity.class);
//startActivity(Screen);
// Toast.makeText(MainActivity.this, "You can use our Screen Light :)",
// Toast.LENGTH_LONG).show();
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleBackground();
//Orientación de la APP Horizontal
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Codigo para que no se apague la pantalla :D
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// 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();
// RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
//layout.setBackgroundResource(R.drawable.slender);
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("MainActivity", "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(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleBackground();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
// playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleBackground();
}
}
// Playing sound
// will play button toggle sound on flash on / off
// private void playSound(){
// if(isFlashOn){
// mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
// }else{
// mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
// }
// mp.setOnCompletionListener(new OnCompletionListener() {
// #Override
// public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// mp.release();
// }
// });
// mp.start();
// }
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleBackground(){
if(isFlashOn){
RelativeLayout layout = (RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.banderausa);
}else{
RelativeLayout layout = (RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.banderausa2);
}
}
#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
//CREO QUE ES PARA QUE SE ENCIENDA APENAS SE ABRE.
if (hasFlash){
turnOnFlash();
} //else {
//Toast.makeText(MainActivity.this, "You can use our Screen Light :)",
// Toast.LENGTH_LONG).show();
//}
}
#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;
}
}
}
Inside your onCreate, you can have a layout's onClickListener on your outermost layout as follows:
RelativeLayout layout=(RelativeLayout)findViewById(R.id.yourRelativeLayout);
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
}
});
You might have to add android:clickable = true from xml or setClickable(true) from code.
I have a Flashlight Activity. Normally it works fine but When I go to any other activity, it stop working!
So I want to refresh the code when I back to the Flashlight Activity.
I think refreshing using onResume() would help me best, But how to do it?
public class FlashLightActivity extends Activity {
//flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private Button next1, next2;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next1 = (Button) findViewById(R.id.ebtn28_answer);
next1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), FullScreen.class);
startActivityForResult(myIntent, 0);
}
});
next2 = (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();
next2.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;
}
}
});
}
}
You need to override onPause and onResume. In onPause, you need to release the Camera. In onResume, you need to re-request it. Camera doesn't like it if you try to hold it when you aren't the active activity.
public void onPause(){
super.onPause();
if(camera != null){
camera.release();
camera = null;
}
}
public void onResume(){
super.onResume();
//Need to release if we already have one, or we won't get the camera
if(camera != null){
camera.release();
camera = null;
}
try {
camera = Camera.open();
}
catch (Exception e){
}
}
I have a button on my camera preview screen to toggle the camera's flash. The camera starts on auto-flash which works then when the button is pressed the flash turns off but when i try to turn the flash back on it doesn't turn on and i don't know why?
Log.d("flash",mCamera.getParameters().getFlashMode());
Displays on off and auto as i press it. But it doesn't turn back on. Here is my full code
public void flashPressed(View v)
{
ImageButton flashButton = (ImageButton)findViewById(R.id.flash);
Camera.Parameters myP = mCamera.getParameters();
if(flashOn == 0)
{
flashButton.setImageResource(R.drawable.device_access_flash_off);
myP.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
flashOn = 1;
}
else if(flashOn == 1)
{
myP.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
flashButton.setImageResource(R.drawable.device_access_flash_on);
flashOn=2;
}else{
myP.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
flashButton.setImageResource(R.drawable.device_access_flash_automatic);
flashOn =0;
}
mCamera.setParameters(myP);
Log.d("flash",mCamera.getParameters().getFlashMode());
}
This is how I used to create a Flash app.
public class Flash extends Activity {
boolean cameraOpened;
static Camera camFlash = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onPause() {
super.onPause();
if (camFlash != null) {
camFlash.stopPreview();
camFlash.release();
camFlash = null;
}
}
public void turnOnFlash(View view) {
if (camFlash == null) {
camFlash = Camera.open();
}
if (camFlash != null) {
Parameters params = camFlash.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camFlash.setParameters(params);
camFlash.startPreview();
camFlash.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
}
public void turnOffFlash(View view) {
if (camFlash != null) {
camFlash.stopPreview();
camFlash.release();
camFlash = null;
}
}
}
the methods turnOnFlash() and turnOffFlash are called from xml android:onClick.
To avoid this problem I just created a new camera each time the flash option changes