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
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
}
}
Ok so first, I have menu with 3 buttons leading to 3 different layouts.
What I want, I want to show interstitial ad when I close my application.
What happens, In order to save memory I had to add finish() on every button so it doesn't take all memory. And when I click on any button interstitial ad shows.
Whats the problem, I can't set my code to show interstitial only when I completely close app not when I switch activities
My code:
package puske.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.ads.*;
import com.google.ads.AdRequest.ErrorCode;
public class Menu extends Activity implements AdListener {
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
interstitial = new InterstitialAd(this, "ID");
// 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) {
{
Button button1=(Button)findViewById(R.id.menu1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Rifles.class));
finish();
}
});
Button button2=(Button)findViewById(R.id.menu2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Pistols.class));
finish();
}
});
Button button4=(Button)findViewById(R.id.menu3);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Snipers.class));
finish();
}
});
}
}
#Override
protected void onDestroy() {
interstitial.show();
super.onDestroy();
// explicitly release media player
unbindDrawables(findViewById(R.id.menuzor));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
try
{
((ViewGroup) view).removeAllViews();
}
catch(UnsupportedOperationException ignore)
{
}
}
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#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 onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
}
Look at this picture
onPause or onStop();
Just try
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.
I am trying to play a sound when button is pressed. To do so, I tried few methods :
1 : Created a MediaPlayer under and played it when button is pressed like this :
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mp.seekTo(0);
mp.start();
}
});
}
This method worked like charm. But then I wanted to conserve memory and wanted to release MediaPlayer when activity is in background. So I added this
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.release();
super.onPause();
}
But now, when activity comes back in foreground it throws an error ( because MediaPlayer is created under OnCreate).
So, I thought to create it under onResume since it is always called.
#Override
protected void onResume() {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
super.onResume();
}
It worked.
Full code is like this :
package com.example.learn;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.release();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
mp = MediaPlayer.create(MainActivity.this, R.raw.bell);
mp.setLooping(false);
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1: {
mp.seekTo(0);
mp.start();
}
}
}
}
just thinking have I done it right? Are there better and easier ways?
By looking on your code I think you have done it in a right way. You can Create that in onResume as it is always called. On Create is Called for the first time only.
And Yes ALWAYS call
mediaPlayer.relaese();
instead of
mediaPlayer.stop();
Everything in your code is looking right. For more accuracy you can have a glance on this
LINK
I am using the following sample code to play a 3gp video. on android 2.3 .. but only the audio is playing, but the video doesn't appear . what is the problem ?
package pit.opensource.video;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
public class L2VideoExampleActivity extends Activity implements SurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;
AudioManager audioManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.volbar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pausing = false;
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
// mediaPlayer.setDataSource(stringPath);
// mediaPlayer.prepare();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.samplevideo);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(pausing){
pausing = false;
mediaPlayer.start();
}
else{
pausing = true;
mediaPlayer.pause();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
I think you must play video in surfaceview.you now play video in oncreate and may be surfaceview not created yet.
use something like this in surfaceCreated
#Override
public void surfaceCreated(SurfaceHolder holder)
{
if(ArrayManager.array_for_playing != null)
if(SDcard.icurrentIndex != -1)
playVideo(SDcard.icurrentIndex);
}
and this is playVideo method
private void playVideo(Integer Media)
{
try {
mPlayer.reset();
mPlayer.setDataSource(ArrayManager.array_for_playing.get(SDcard.icurrentIndex).getPath());
mPlayer.setDisplay(holder);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
mPlayer.prepare();
mPlayer.start();
btnPlay.setBackgroundResource(R.drawable.img_btn_pause);
// Updating progress bar
updateProgressBar();
}
catch (Exception e)
{
Log.e("video player", "error: " + e.getMessage(), e);
}
}
And in IniatializeUi method
private void InitializeUI()
{
mPreview = (SurfaceView) findViewById(R.id.surface_view);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
and in top of activity :
private SurfaceView mPreview;
private SurfaceHolder holder;
I hope this help users.