i am doing a FlashLight and when a friend try it, he got a crash.
He have V 4.0+
Here my logcat:
https://github.com/Hersix/LogCat-FlashLightAPP/commit/9fa44813cdad14f461c14070cc0eea6e8c29c93a
I am newbie, but i read that Apps with Threads in version 4.0+ Crashes, so.. i don´t understand good, but, how can i put all my code without a thread ?
This is my app code:
package flash.light.app;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
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);
final AdView adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest());
ImageView ButtonScr = (ImageView) findViewById(R.id.imageView1);
ButtonScr.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent Screen = new Intent (MainActivity.this, ScreenActivity.class);
startActivity(Screen);
}});
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.imageButton1);
// 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
toggleButtonImage();
//Orientación de la APP Vertical
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//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();
// RelativeLayout layout = (RelativeLayout)findViewById(R.id.background);
// layout.setBackgroundResource(R.drawable.image6);
} 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("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.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 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();
// 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;
}
}
}
How can i do, to run a SIMPLE app (like this, its a simple flashlight) in ALL or almost all devices?
Thanks and sorry for my english
your issue is in getCamera(), in the line Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
it looks like e.getMessage() is returning null, hence the crash.
you should probably use the format Log.e(TAG, "getCamera", e); which will print the stack trace for the exception (and not crash your app)
Replace
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
with
Log.e("MainActivity", "Camera Error. Failed to Open. Error: " + e.getMessage());
then figure out why the camera doesn't work.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have created simple flashlight app. There isn't any error at compile. but when the icon is clicked it just stop unexpectedly. I have tried in both physical android phone and emulator. both comes up with same result. I cant see any problem in the code. can someone recify this problem.
Flashlight.java (Activity)
package flashlight.turnmeyon.crystal.laser;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
public class Flashlight extends AppCompatActivity {
ImageButton imagebutton;
Camera camera;
Camera.Parameters parameters;
boolean isflash = false;
boolean ison = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_flashlight);
imagebutton = (ImageButton) findViewById(R.id.buttonOn);
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
camera.open();
parameters = camera.getParameters();
isflash = true;
}
imagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isflash) {
if (!ison) {
imagebutton.setImageResource(R.drawable.buttonon);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
ison = true;
} else {
imagebutton.setImageResource(R.drawable.buttonof);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
ison = false;
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(Flashlight.this);
builder.setTitle("Error...........");
builder.setMessage("Flashlight is not avaliable");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertdialog = builder.create();
alertdialog.show();
}
}
});
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#757575"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageButton
android:id="#+id/buttonOn"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#757575"
android:src="#drawable/buttonof"
android:scaleType="fitCenter"
android:layout_marginTop="80dp"
android:layout_marginRight="80dp"
android:layout_marginLeft="80dp"
android:layout_marginBottom="40dp"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Here is reference for you.
I created Flash Example. Please review below code.
public class MainActivity extends AppCompatActivity {
ImageView switch_on_off;
private Camera camera;
Parameters params;
public boolean isSupportFlash, isFlashLighOn;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isSupportFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isSupportFlash) {
Toast.makeText(getApplicationContext(), "Your device does not support flash. ", Toast.LENGTH_LONG).show();
}
switch_on_off = (ImageView) findViewById(R.id.switch_on_off);
connectCameraService();
switch_on_off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashLighOn) {
offFlashLight();
switch_on_off.setImageResource(R.drawable.switch_off);
} else {
onFlashLight();
switch_on_off.setImageResource(R.drawable.switch_on);
}
}
});
}
public void onFlashLight() {
if (!isFlashLighOn) {
status = "ON";
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashLighOn = true;
switch_on_off.setImageResource(R.drawable.switch_on);
}
}
public void offFlashLight() {
if (isFlashLighOn) {
status = "ON";
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashLighOn = false;
switch_on_off.setImageResource(R.drawable.switch_off);
}
}
public void connectCameraService() {
if (camera == null) {
camera = android.hardware.Camera.open();
params = camera.getParameters();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
offFlashLight();
}
#Override
protected void onPause() {
super.onPause();
offFlashLight();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
/*if (isSupportFlash) {
onFlashLight();
}*/
}
#Override
protected void onStart() {
super.onStart();
connectCameraService();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
Required permission
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Create a simple Torch application which can put on the Camera Flash and put it off. This application should have a simple UI which can put On the Flash and also put it Off.
After 1 minute of continuous use, the UI should prompt the user he wants to keep use the Torch. If the user says Yes the Torch shall remain on for another minute and this cycle shall repeat. If the user says No, the Torch shall be put off.
Creating a simple torch app is easy and I have made torch app but the second thing which is mentioned in the question to make a prompt after 1 minute that thing I am not able to understand can anyone help?
here is my code of flashlight can anyone tell me where to change in it.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
`enter code here`private boolean isLightOn=false;
private Camera camera;
private Button btn;
#Override
protected void onStop()
{
super.onStop();
if(camera!= null)
camera.release();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
Context context=this;
PackageManager pk= context.getPackageManager();
if(!pk.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Log.e("err","Device has no camera");
return;
}
camera=camera.open();
final Parameters p= camera.getParameters();
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(isLightOn)
{
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
else
{
Log.i("info","FlashLight is turn On!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn=true;
}
}
});
}
}
First create a XML having a switch widget. Then connect it with Java, Using onOffSwitch = (Switch) findViewById(R.id.switch1);
Get CameraManager so that u can manage camera's element(which is the flashLight), Using mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
3.Get current phone's camera ID so that you can instruct android which camera to Point , Using mCameraId = mCameraManager.getCameraIdList()[0];
Turn on using : mCameraManager.setTorchMode(mCameraId, true);
Turn off Using : mCameraManager.setTorchMode(mCameraId, false);
Code:
public class TorchActivity extends AppCompatActivity {
CameraManager mCameraManager;
String mCameraId;
Switch onOffSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_torch);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
onOffSwitch = (Switch) findViewById(R.id.switch1);
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean isFlashAvailable = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (isFlashAvailable)
{
onOffSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffSwitch.isChecked()) {
try {
mCameraManager.setTorchMode(mCameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
else{
try {
mCameraManager.setTorchMode(mCameraId, false);
}
catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
});
}else
{
Toast.makeText(this, "No Flash Support Found!", Toast.LENGTH_SHORT).show();
}
}
//Use these permissions!
Min SDK should be - 23
//<uses-permission android:name="android.permission.CAMERA" />
//<uses-permission android:name="android.permission.FLASHLIGHT" />
//<uses-feature android:name="android.hardware.camera" />
//<uses-feature android:name="android.hardware.camera.flash" />
if(!pk.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Log.e("err","Device has no camera");
return;
}
camera=camera.open();
final Parameters p= camera.getParameters();
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(isLightOn)
{
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
else
{
Log.i("info","FlashLight is turn On!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn=true;
new Handler().postDelayed(new Runnable() {
// Using handler with postDelayed called runnable run method
#Override
public void run() {
//Show your Alert box here
new AlertDialog.Builder(context) // you can use getApplicationContext() or your activityname.this as context
.setTitle("Do You Want to continue")
.setMessage("Are you sure you want to continue?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Do nothing, Torch continues
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// torch off
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}, 60000); //60000milliseconds = 60 sec = 1min.
// It will show alertbox after 1 min .
}
}
});
}
}
To run some code after a certain delay, you can do the following (where 1000 is the delay in milliseconds):
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
// code to show prompt goes here
}
}, 1000);
You can make this into a method, which gets called each time the user acknowledges the prompt.
For dialog box check this.
Check this link for flash On/Off.
for Flash Off after one min use Handler.
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Turn off flash
}
};
handler.postDelayed(r, 1000);
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
}
}
i ask here because i can't put instertital ads in my app. I get like 20 errors when i put the code below the saved Instance.
I had other app and i never had problems, but now i just can't.
In the section of Toast (below ad code) i get this error:
Multiple markers at this line
- Syntax error on token "(", invalid VariableDeclaratorId
- Syntax error on tokens, delete these tokens
- Syntax error on token "makeText", Identifier expected after
this token
- Syntax error on token ")", delete this token
Below toast, on btnSwitch i get this errors:
Multiple markers at this line
- Return type for the method is missing
- Syntax error on token ".", ... expected
- Syntax error on token ")", { expected after this token
- Syntax error on token "btnSwitch", VariableDeclaratorId expected after
this token
- Syntax error, insert ";" to complete FieldDeclaration
package lol.flashlight;
Then here:
ImageView Facebook = (ImageView) findViewById(R.id.imageView3);
Facebook.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
i get this errors:
Multiple markers at this line
- Syntax error, insert "}" to complete
MethodBody
- Syntax error, insert ")" to complete
Expression
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
...I get MORE errors
I tried to put it at the final but anyway i get these errors, what can i do?
I let my full code if u wanna check:
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AdListener {
ImageView btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the interstitial
interstitial = new InterstitialAd(this, "fgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfgfg");
// 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);
}
#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
}
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();
}});
//OnClick del View :D
// ImageView Mundo = (ImageView) findViewById(R.id.imageView6);
// Mundo.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// TODO Auto-generated method stub
//
// mp = MediaPlayer.create(MainActivity.this, R.raw.mundo);
//mp.setOnCompletionListener(new OnCompletionListener() {
// #Override
// public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// mp.release();
// }
// });
// mp.start();
//}});
//OnClick del View :D
// ImageView Orianna = (ImageView) findViewById(R.id.imageView7);
// Orianna.setOnClickListener(new OnClickListener(){
//public void onClick(View v) {
// TODO Auto-generated method stub
// mp = MediaPlayer.create(MainActivity.this, R.raw.orianna);
// 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;
}
}
}
your imports here are wrong, because they import from legacy admob:
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
You have to import from .gms Google Play Services Admob:
import com.google.android.gms.ads.*
Also note that all the code below Toast.makeText(MainActivity.this, "Touch amumu's body to play a sound!", Toast.LENGTH_SHORT).show(); in your example is outside of any method (!) ..this is causing the dozens of compile errors. ==> move that code into some method
*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.