libgdx interstitial ads with admob [duplicate] - java

I found a Flappy Bird GitHub project and changed it a little bit.
I successfully implemented the AdMob Banner.
But now I also want a Interstitial Ad which pops up when the Game is over (not every time of course) so here is my GitHub project: https://github.com/DaFaack/FlappyBibi
Please explain me how to do it because I can't find a good explanation on the internet.
I want to display the ad in the run() method. You can find it in the core package -> GameplayScreen.java File -> renderPlaying() method and then the run() method.
This is the method i am talking about:
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
What do I have to do to display the Interstitial Ad when the game is over?
This is my AndroidLauncher.java file:
package com.pentagames.flappybibi.android;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.pentagames.flappybibi.FlappyGame;
public class AndroidLauncher extends AndroidApplication{
private static final String TAG = "AndroidLauncher";
protected AdView adView;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView=initializeForView(new FlappyGame(), config);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
int visibility = adView.getVisibility();
adView.setVisibility(AdView.GONE);
adView.setVisibility(AdView.VISIBLE);
Log.i(TAG, "Ad Loaded...");
}
});
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXX/XXXXXXXXX");
AdRequest.Builder builder = new AdRequest.Builder();
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layout.addView(adView, adParams);
adView.loadAd(builder.build());
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}
#Override
protected void onPause() {
super.onPause();
adView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
}
And this the GameplayScreen file:
package com.pentagames.flappybibi;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
public class GameplayScreen extends ScreenAdapter{
public static final float PIPE_SPACING = 200f;
public static final int PIPE_SETS = 3;
protected OrthographicCamera camera;
protected com.pentagames.flappybibi.FlappyGame game;
private Stage gameplayStage;
private Stage uiStage;
private Label scoreLabel;
private Label tapToRetry;
private Label best;
private Label tapToFlap;
private Image whitePixel;
private Image backgroundBuildings;
private int score;
private Bird bird;
private Array<PipePair> pipePairs;
private com.pentagames.flappybibi.Ground ground;
private boolean justTouched;
private Color backgroundColor;
private State screenState = State.PREGAME;
private boolean allowRestart = false;
private enum State {PREGAME, PLAYING, DYING, DEAD}
public GameplayScreen(com.pentagames.flappybibi.FlappyGame game) {
this.game = game;
camera = new OrthographicCamera(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT, camera));
uiStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT));
bird = new Bird();
bird.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH * .25f, com.pentagames.flappybibi.FlappyGame.HEIGHT / 2, Align.center);
bird.addAction(Utils.getFloatyAction());
bird.setState(Bird.State.PREGAME);
whitePixel = new Image(com.pentagames.flappybibi.Assets.whitePixel);
scoreLabel = new Label("0", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
uiStage.addActor(scoreLabel);
tapToRetry = new Label("Nochmal?", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToRetry.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(tapToRetry);
best = new Label("Highscore: ", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
best.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(best);
tapToFlap = new Label("Fass mich an!", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToFlap.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom);
uiStage.addActor(tapToFlap);
initBackgroundBuildings();
pipePairs = new Array<PipePair>();
ground = new com.pentagames.flappybibi.Ground();
ground.setPosition(0, 0);
backgroundColor = Utils.getRandomBackgroundColor();
// The order actors are added determines the order they are drawn so make sure the background is first
gameplayStage.addActor(ground);
gameplayStage.addActor(backgroundBuildings);
gameplayStage.addActor(bird);
// Setup the input processor
initInputProcessor();
}
private void initBackgroundBuildings() {
backgroundBuildings = new Image(com.pentagames.flappybibi.Assets.backgroundBuildings);
backgroundBuildings.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
backgroundBuildings.setHeight(backgroundBuildings.getHeight()*2f);
backgroundBuildings.setY(com.pentagames.flappybibi.Ground.HEIGHT);
}
#Override
public void show() {
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y + 100f, Align.center, .75f, Interpolation.sine));
com.pentagames.flappybibi.Assets.playWooshSound();
}
#Override
public void render(float delta) {
Gdx.graphics.getGL20().glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
switch (screenState) {
case PREGAME:
updateAndDrawStages();
break;
case PLAYING:
renderPlaying();
break;
case DYING:
case DEAD:
renderDeadOrDying();
break;
}
}
private void renderDeadOrDying() {
if (bird.getState() == Bird.State.DEAD) {
screenState = State.DEAD;
}
updateAndDrawStages();
}
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
SequenceAction actions = Actions.sequence(Actions.delay(1f), playWooshAction, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.bottom,
.75f, Interpolation.sine), Actions.run(new Runnable() {
#Override
public void run() {
// Allow the player to restart the game once the tap to retry finishes coming up
allowRestart = true;
}
}));
tapToRetry.addAction(actions);
best.setText("Highscore: " + com.pentagames.flappybibi.SavedDataManager.getInstance().getHighScore());
best.setWidth(best.getTextBounds().width);
best.setPosition(com.pentagames.flappybibi.FlappyGame.CENTER_X, 0, Align.top);
best.addAction(Actions.delay(1f, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.top,
.75f, Interpolation.sine)));
screenState = State.DYING;
}
gameplayStage.draw();
uiStage.draw();
}
private void updateAndDrawStages() {
gameplayStage.act();
gameplayStage.draw();
uiStage.act();
uiStage.draw();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
com.pentagames.flappybibi.Assets.batch.setProjectionMatrix(camera.combined);
gameplayStage.getViewport().update(width, height, true);
uiStage.getViewport().update(width, height, true);
}
#Override
public void dispose() {
gameplayStage.dispose();
uiStage.dispose();
}
private void checkCollisions() {
for (int i = 0; i < pipePairs.size; i++) {
PipePair pair = pipePairs.get(i);
if (pair.getBottomPipe().getBounds().overlaps(bird.getBounds()) || pair.getTopPipe().getBounds().overlaps(bird.getBounds())) {
stopTheWorld();
com.pentagames.flappybibi.SavedDataManager.getInstance().setHighScore(score);
showWhiteScreen();
} else if (bird.isBelowGround()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.GROUND_LEVEL);
bird.clearActions();
bird.setToDying();
showWhiteScreen();
} else if (bird.isAboveCeiling()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.HEIGHT - bird.getHeight());
bird.setToDying();
showWhiteScreen();
} else if (pair.getRuby().getBounds().overlaps(bird.getBounds())) {
score++;
updateScoreLabel();
pair.moveCoinOffscreen();
com.pentagames.flappybibi.Assets.playBingSound();
}
}
}
private void showWhiteScreen() {
whitePixel.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
whitePixel.setHeight(com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage.addActor(whitePixel);
whitePixel.addAction(Actions.fadeOut(.5f));
}
private void updateScoreLabel() {
scoreLabel.setText(String.valueOf(score));
scoreLabel.setWidth(scoreLabel.getTextBounds().width);
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
}
private void stopTheWorld() {
bird.setToDying();
killPipePairs();
stopTheGround();
screenState = State.DYING;
}
private void stopTheGround() {
ground.vel.x = 0;
}
private void killPipePairs() {
for (PipePair pair : pipePairs) {
pair.getBottomPipe().setState(Pipe.State.dead);
pair.getTopPipe().setState(Pipe.State.dead);
pair.getRuby().setVel(0, 0);
}
}
private void updatePipePairs() {
for (int i = 0; i < pipePairs.size; i++) {
pipePairs.get(i).update();
}
}
private void addPipes(Stage gameplayStage) {
for (int i = 0; i < pipePairs.size; i++) {
gameplayStage.addActor(pipePairs.get(i).getBottomPipe());
gameplayStage.addActor(pipePairs.get(i).getTopPipe());
gameplayStage.addActor(pipePairs.get(i).getRuby());
}
}
private void initThirdSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initThird();
// add the pair to the list
pipePairs.add(pair);
}
private void initSecondSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initSecond();
// add the pair to the list
pipePairs.add(pair);
}
private void initFirstSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initFirst();
// add the pair to the list
pipePairs.add(pair);
}
/**
* Tells libgdx to listen for inputs coming from the InputAdapter we give it
*/
private void initInputProcessor() {
Gdx.input.setInputProcessor(new InputAdapter() {
// We only care about the touch down event
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
switch (screenState) {
case DYING:
justTouched = true;
break;
case DEAD:
if (allowRestart) {
game.setScreen(new GameplayScreen(game));
}
justTouched = true;
break;
case PLAYING:
justTouched = true;
break;
case PREGAME:
justTouched = true;
screenState = State.PLAYING;
bird.setState(Bird.State.ALIVE);
bird.clearActions();
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom, .75f, Interpolation.sine));
initFirstSetOfPipes();
initSecondSetOfPipes();
initThirdSetOfPipes();
addPipes(gameplayStage);
gameplayStage.addActor(ground);
gameplayStage.addActor(bird);
break;
}
return true;
}
});
}
}
This is the first time that I'm working with LibGDX, would be great if you can explain me how to implement the Interstitial Ad in this project.
Sorry for my bad English.

You already integrated banner Ad so no need to injected dependent artifact in your project.
Follow these steps for Interstitial Ad integration.
AndroidManifest.xml
Make an entry of AdActivity for Interstitial Ad
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
Create an interface inside your core module
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
Create a parameterized constructor of FlappyGame class
public AdService adService;
public FlappyGame(AdService ads){
adService=ads;
}
Implement AdService interface to your AndroidLauncher class
public class AndroidLauncher extends AndroidApplication implements AdService {
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-XXXXX/XXXXX";
private InterstitialAd interstitialAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
View gameView=initializeForView(new FlappyGame(this), config);
...
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
GameScreen class
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
game.adService.showInterstitial();
}
});
I integrated Interstitial Ad in your project, created a pull request for the same. You can merge my pull request.

Related

order and timing of command execution bug

I'm making a "Simon says" game as my final project for highschool, and it's mostly done but I have one problem.
Currently, I'm trying to make the buttons light when I press them.
However, they don't seem to light up and the sleep function doesn't really work.
They only change color when the function that displays the next sequence of colors lights up.
Here's the code:
package com.gabie212.simonsays;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements View.OnClickListener {
private int i = 0, pNum = 0, pIndex = 0,score;
private Thread t = new Thread();
private Thread bt = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private TextView Score;
private boolean startActivated = false;
private MediaPlayer greenBeep;
private MediaPlayer redBeep;
private MediaPlayer blueBeep;
private MediaPlayer yellowBeep;
private ArrayList<Integer> userColors = new ArrayList<Integer>();
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Score = (TextView) findViewById(R.id.ScoreNum);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
startButton.setOnClickListener(this);
greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
redBeep = MediaPlayer.create(this, R.raw.redbeep);
blueBeep = MediaPlayer.create(this, R.raw.bluebeep);
yellowBeep = MediaPlayer.create(this, R.raw.yellowbeep);
/*
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.apply();
*/
}
public void start() {
startActivated=true;
gm = new GameManger(this);
Score.setText("0");
lightUp(0);
}
public void beepStop(){
greenBeep.stop();
redBeep.stop();
blueBeep.stop();
yellowBeep.stop();
}
public void lightUp(final int i) {
android.os.Handler handler = new android.os.Handler();
if (i < gm.getRandomColors().size()) //light up code
{
switch (gm.getRandomColors().get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
greenBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
lightUp(i+1);
}
}, 500);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
redBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
lightUp(i+1);
}
}, 500);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
blueBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
lightUp(i+1);
}
}, 500);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
yellowBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
lightUp(i+1);
}
}, 500);
break;
}
}
pIndex = 0;
}
#Override
public void onClick(View v) {
if (v.getId() == startButton.getId()) {
start();
} else {
if (startActivated) {
if (v.getId() == greenButton.getId()) {//here is the part where i try to make the buttons change colors
greenBeep.start();
greenButton.setBackgroundResource(R.drawable.greenlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
greenButton.setBackgroundResource(R.drawable.green);
pNum = 1;
}
if (v.getId() == redButton.getId()) { //here is the part where i try to make the buttons change colors
redBeep.start();
redButton.setBackgroundResource(R.drawable.redlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
redButton.setBackgroundResource(R.drawable.red);
pNum = 2;
}
if (v.getId() == blueButton.getId()) { //here is the part where i try to make the buttons change colors
blueBeep.start();
blueButton.setBackgroundResource(R.drawable.bluelightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
blueButton.setBackgroundResource(R.drawable.blue);
pNum = 3;
}
if (v.getId() == yellowButton.getId()) {//here is the part where i try to make the buttons change colors
yellowBeep.start();
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
yellowButton.setBackgroundResource(R.drawable.yellow);
pNum = 4;
}
if (!gm.check(pNum, pIndex)) {
beepStop();
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
Intent i = null;
score = gm.getRandomColors().size()-1;
if(score > sp.getInt("scoreP3",0)) {
i = new Intent(GameActivity.this, InsertScoreActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
else {
i = new Intent(GameActivity.this, GameOverActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
}
pIndex++;
if (pIndex == gm.getRandomColors().size()) {
Score.setText("" + gm.getRandomColors().size() + "");
gm.addColor();
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
lightUp(0);//it either performs the color change here beofre the lightup function or it just sleeps and doesn't perform the color change at all
}
}
}
}
}
here's the game helper class:
package com.gabie212.simonsays;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by Ronit on 21/02/2018.
*/
public class GameManger {
private GameActivity gActivity;
static Random rnd = new Random();
private ArrayList<Integer> randomColors;
public GameManger(GameActivity mA)
{
randomColors = new ArrayList<Integer>();
this.gActivity =mA;
randomColors.add(getColor());
}
public void addColor()
{
randomColors.add(getColor());
}
public int getColor()
{
return rnd.nextInt(4)+1;
}
public ArrayList<Integer> getRandomColors()
{
return randomColors;
}
public boolean check(int num, int index)
{
return(randomColors.get(index)==num);
}
}
enter code here
I have some problems.
The sleep doesn't perform, does it have something to do with the way I did it in the if statements? Sleep just doesn't happen in the code I have written.
Color change doesn't happen for some reason and I don't know why it doesn't, maybe it has something to do with the thread.sleep.
Color change happens later in the program than its supposed to. Again, I think it has something to do with the sleep but when I removed the sleep, the color change still happens later in the code.

How to display a Interstitial Ad in a LibGDX project?

I found a Flappy Bird GitHub project and changed it a little bit.
I successfully implemented the AdMob Banner.
But now I also want a Interstitial Ad which pops up when the Game is over (not every time of course) so here is my GitHub project: https://github.com/DaFaack/FlappyBibi
Please explain me how to do it because I can't find a good explanation on the internet.
I want to display the ad in the run() method. You can find it in the core package -> GameplayScreen.java File -> renderPlaying() method and then the run() method.
This is the method i am talking about:
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
What do I have to do to display the Interstitial Ad when the game is over?
This is my AndroidLauncher.java file:
package com.pentagames.flappybibi.android;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.pentagames.flappybibi.FlappyGame;
public class AndroidLauncher extends AndroidApplication{
private static final String TAG = "AndroidLauncher";
protected AdView adView;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView=initializeForView(new FlappyGame(), config);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
int visibility = adView.getVisibility();
adView.setVisibility(AdView.GONE);
adView.setVisibility(AdView.VISIBLE);
Log.i(TAG, "Ad Loaded...");
}
});
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXX/XXXXXXXXX");
AdRequest.Builder builder = new AdRequest.Builder();
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layout.addView(adView, adParams);
adView.loadAd(builder.build());
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}
#Override
protected void onPause() {
super.onPause();
adView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
}
And this the GameplayScreen file:
package com.pentagames.flappybibi;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
public class GameplayScreen extends ScreenAdapter{
public static final float PIPE_SPACING = 200f;
public static final int PIPE_SETS = 3;
protected OrthographicCamera camera;
protected com.pentagames.flappybibi.FlappyGame game;
private Stage gameplayStage;
private Stage uiStage;
private Label scoreLabel;
private Label tapToRetry;
private Label best;
private Label tapToFlap;
private Image whitePixel;
private Image backgroundBuildings;
private int score;
private Bird bird;
private Array<PipePair> pipePairs;
private com.pentagames.flappybibi.Ground ground;
private boolean justTouched;
private Color backgroundColor;
private State screenState = State.PREGAME;
private boolean allowRestart = false;
private enum State {PREGAME, PLAYING, DYING, DEAD}
public GameplayScreen(com.pentagames.flappybibi.FlappyGame game) {
this.game = game;
camera = new OrthographicCamera(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT, camera));
uiStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT));
bird = new Bird();
bird.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH * .25f, com.pentagames.flappybibi.FlappyGame.HEIGHT / 2, Align.center);
bird.addAction(Utils.getFloatyAction());
bird.setState(Bird.State.PREGAME);
whitePixel = new Image(com.pentagames.flappybibi.Assets.whitePixel);
scoreLabel = new Label("0", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
uiStage.addActor(scoreLabel);
tapToRetry = new Label("Nochmal?", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToRetry.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(tapToRetry);
best = new Label("Highscore: ", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
best.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(best);
tapToFlap = new Label("Fass mich an!", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToFlap.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom);
uiStage.addActor(tapToFlap);
initBackgroundBuildings();
pipePairs = new Array<PipePair>();
ground = new com.pentagames.flappybibi.Ground();
ground.setPosition(0, 0);
backgroundColor = Utils.getRandomBackgroundColor();
// The order actors are added determines the order they are drawn so make sure the background is first
gameplayStage.addActor(ground);
gameplayStage.addActor(backgroundBuildings);
gameplayStage.addActor(bird);
// Setup the input processor
initInputProcessor();
}
private void initBackgroundBuildings() {
backgroundBuildings = new Image(com.pentagames.flappybibi.Assets.backgroundBuildings);
backgroundBuildings.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
backgroundBuildings.setHeight(backgroundBuildings.getHeight()*2f);
backgroundBuildings.setY(com.pentagames.flappybibi.Ground.HEIGHT);
}
#Override
public void show() {
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y + 100f, Align.center, .75f, Interpolation.sine));
com.pentagames.flappybibi.Assets.playWooshSound();
}
#Override
public void render(float delta) {
Gdx.graphics.getGL20().glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
switch (screenState) {
case PREGAME:
updateAndDrawStages();
break;
case PLAYING:
renderPlaying();
break;
case DYING:
case DEAD:
renderDeadOrDying();
break;
}
}
private void renderDeadOrDying() {
if (bird.getState() == Bird.State.DEAD) {
screenState = State.DEAD;
}
updateAndDrawStages();
}
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
SequenceAction actions = Actions.sequence(Actions.delay(1f), playWooshAction, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.bottom,
.75f, Interpolation.sine), Actions.run(new Runnable() {
#Override
public void run() {
// Allow the player to restart the game once the tap to retry finishes coming up
allowRestart = true;
}
}));
tapToRetry.addAction(actions);
best.setText("Highscore: " + com.pentagames.flappybibi.SavedDataManager.getInstance().getHighScore());
best.setWidth(best.getTextBounds().width);
best.setPosition(com.pentagames.flappybibi.FlappyGame.CENTER_X, 0, Align.top);
best.addAction(Actions.delay(1f, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.top,
.75f, Interpolation.sine)));
screenState = State.DYING;
}
gameplayStage.draw();
uiStage.draw();
}
private void updateAndDrawStages() {
gameplayStage.act();
gameplayStage.draw();
uiStage.act();
uiStage.draw();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
com.pentagames.flappybibi.Assets.batch.setProjectionMatrix(camera.combined);
gameplayStage.getViewport().update(width, height, true);
uiStage.getViewport().update(width, height, true);
}
#Override
public void dispose() {
gameplayStage.dispose();
uiStage.dispose();
}
private void checkCollisions() {
for (int i = 0; i < pipePairs.size; i++) {
PipePair pair = pipePairs.get(i);
if (pair.getBottomPipe().getBounds().overlaps(bird.getBounds()) || pair.getTopPipe().getBounds().overlaps(bird.getBounds())) {
stopTheWorld();
com.pentagames.flappybibi.SavedDataManager.getInstance().setHighScore(score);
showWhiteScreen();
} else if (bird.isBelowGround()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.GROUND_LEVEL);
bird.clearActions();
bird.setToDying();
showWhiteScreen();
} else if (bird.isAboveCeiling()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.HEIGHT - bird.getHeight());
bird.setToDying();
showWhiteScreen();
} else if (pair.getRuby().getBounds().overlaps(bird.getBounds())) {
score++;
updateScoreLabel();
pair.moveCoinOffscreen();
com.pentagames.flappybibi.Assets.playBingSound();
}
}
}
private void showWhiteScreen() {
whitePixel.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
whitePixel.setHeight(com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage.addActor(whitePixel);
whitePixel.addAction(Actions.fadeOut(.5f));
}
private void updateScoreLabel() {
scoreLabel.setText(String.valueOf(score));
scoreLabel.setWidth(scoreLabel.getTextBounds().width);
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
}
private void stopTheWorld() {
bird.setToDying();
killPipePairs();
stopTheGround();
screenState = State.DYING;
}
private void stopTheGround() {
ground.vel.x = 0;
}
private void killPipePairs() {
for (PipePair pair : pipePairs) {
pair.getBottomPipe().setState(Pipe.State.dead);
pair.getTopPipe().setState(Pipe.State.dead);
pair.getRuby().setVel(0, 0);
}
}
private void updatePipePairs() {
for (int i = 0; i < pipePairs.size; i++) {
pipePairs.get(i).update();
}
}
private void addPipes(Stage gameplayStage) {
for (int i = 0; i < pipePairs.size; i++) {
gameplayStage.addActor(pipePairs.get(i).getBottomPipe());
gameplayStage.addActor(pipePairs.get(i).getTopPipe());
gameplayStage.addActor(pipePairs.get(i).getRuby());
}
}
private void initThirdSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initThird();
// add the pair to the list
pipePairs.add(pair);
}
private void initSecondSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initSecond();
// add the pair to the list
pipePairs.add(pair);
}
private void initFirstSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initFirst();
// add the pair to the list
pipePairs.add(pair);
}
/**
* Tells libgdx to listen for inputs coming from the InputAdapter we give it
*/
private void initInputProcessor() {
Gdx.input.setInputProcessor(new InputAdapter() {
// We only care about the touch down event
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
switch (screenState) {
case DYING:
justTouched = true;
break;
case DEAD:
if (allowRestart) {
game.setScreen(new GameplayScreen(game));
}
justTouched = true;
break;
case PLAYING:
justTouched = true;
break;
case PREGAME:
justTouched = true;
screenState = State.PLAYING;
bird.setState(Bird.State.ALIVE);
bird.clearActions();
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom, .75f, Interpolation.sine));
initFirstSetOfPipes();
initSecondSetOfPipes();
initThirdSetOfPipes();
addPipes(gameplayStage);
gameplayStage.addActor(ground);
gameplayStage.addActor(bird);
break;
}
return true;
}
});
}
}
This is the first time that I'm working with LibGDX, would be great if you can explain me how to implement the Interstitial Ad in this project.
Sorry for my bad English.
You already integrated banner Ad so no need to injected dependent artifact in your project.
Follow these steps for Interstitial Ad integration.
AndroidManifest.xml
Make an entry of AdActivity for Interstitial Ad
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
Create an interface inside your core module
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
Create a parameterized constructor of FlappyGame class
public AdService adService;
public FlappyGame(AdService ads){
adService=ads;
}
Implement AdService interface to your AndroidLauncher class
public class AndroidLauncher extends AndroidApplication implements AdService {
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-XXXXX/XXXXX";
private InterstitialAd interstitialAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
View gameView=initializeForView(new FlappyGame(this), config);
...
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
GameScreen class
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
game.adService.showInterstitial();
}
});
I integrated Interstitial Ad in your project, created a pull request for the same. You can merge my pull request.

Latitude and longitude per pixel Google static maps

I have a static map, i know center coordinates in latitude and longitude, zoom level and image dimensions.
I don't understood if google static maps are already flattened and latitude and longitude per pixel are the same anywhere. If it's not like that i whant to know how can i calculate latidude and longitude per pixel and then meters per pixel , and how does that values vary with latitude .
P.S. I'm developing an android application that download an static map and computes distance between 2 points , but i've done that asuming the lat and long per pixel are the same ...and doesn't depend on latitude(position on globe)
Here is my mainactivity
package com.mnav.nav;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
import java.net.*;
import org.apache.http.*;
import android.graphics.*;
import java.io.*;
import android.graphics.drawable.*;
public class MainActivity extends Activity
{ Button start, dist;
TextView txt;
EditText lat, longit, zoom;
ImageView img;
Handler mhandler ;
Bitmap bit, original;
Boolean run = false, firstpoint = false, secondpoint = false;
String z, latitude, longitude;
int level;
int[] pointa = new int[2];
int[] pointb = new int[2];
double unit;
int maxx, maxy, minx, miny, distx, disty, distance1;
double distance;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(Button)findViewById(R.id.button);
lat = (EditText)findViewById(R.id.latitude);
longit = (EditText)findViewById(R.id.longitude);
img = (ImageView)findViewById(R.id.img);
zoom =(EditText)findViewById(R.id.zoom);
dist = (Button)findViewById(R.id.dist);
txt = (TextView)findViewById(R.id.txt);
mhandler = new Handler();
start.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{ z = zoom.getText().toString();
latitude = lat.getText().toString();
longitude = longit.getText().toString();
Thread thr = new Thread(new GetImage());
thr.start();
}
});
img.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{ int i, j;
int x = (int)event.getX();
int vertical = (int)event.getY();
if(secondpoint==true)
{ bit = original.copy(Bitmap.Config.ARGB_4444, true);
img.setImageBitmap(bit);
secondpoint = false;
}
txt.setText(Integer.toString(x)+ " "+Integer.toString(vertical));
for (i = x-2; i < x+3; i++)
{
for(j=vertical-2; j<vertical+3; j++)
{
bit.setPixel(i,j, Color.WHITE);
}
}
bit.setPixel(x,vertical,Color.GREEN);
img.setImageBitmap(bit);
if(firstpoint)
{
pointb[0] = x; pointb[1]=vertical;
secondpoint = true;
firstpoint = false;
}
else
{
pointa[0]=x; pointa[1]=vertical;
firstpoint=true;
}
return false;
}
});
dist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View p1)
{
unit = 0.1412/800;
unit = unit*500;
level = Integer.parseInt(z);
if(level == 20)
{
unit = unit;
}
else
if(level == 19)
{
unit = unit*2;
}
else
if(level==18)
{
unit = unit*4;
}
else
if(level == 17)
{
unit =unit*8;
}
else
if(level==16)
{
unit = unit*16;
}
else
if(level==15)
{
unit = unit*32;
}
else
if(level==14)
{
unit = unit*64;
}
else
if(level==13)
{
unit = unit*128;
}
else
if(level == 12)
{
unit = unit*256;
}
else
if(level==11)
{
unit = unit*512;
}
else
if(level==10)
{
unit = unit*1024;
}
distx = Math.abs(pointa[0]-pointb[0]);
disty= Math.abs(pointa[1]-pointb[1]);
distance1 = distx*distx+disty*disty;
distance = Math.sqrt(distance1);
distance = unit*distance;
txt.setText(Double.toString(distance)+" meters");
}
});
}
public class GetImage implements Runnable
{
String Url = "http://maps.google.com/staticmap?center=" + latitude+","+longitude+"&format=png&zoom="+ z +"&size=500x500&scale=1&maptype=hybrid&key=ABQIAAAA-O3c-Om9OcvXMOJXreXHAxRexG7zW5nSjltmIc1ZE-b8yotBWhQYQEU3J87QIBc4nfuySpoW_K6woA";
Bitmap bmp;
#Override
public void run()
{
try
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
txt.setText("Wait...file is downloading...");
}
});
bmp = BitmapFactory.decodeStream((InputStream)new URL(Url).getContent());
}
catch (IOException e)
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
// TODO: Implement this method
Toast.makeText(getApplicationContext(), "Something wrong just happend", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
mhandler.post(new Runnable()
{
#Override
public void run()
{
if (bmp!=null)
{ txt.setText("Map downloaded..");
img.setImageBitmap(bmp);
bit = ((BitmapDrawable)img.getDrawable()).getBitmap();
bit = bit.copy(Bitmap.Config.ARGB_4444, true);
original = bit.copy(Bitmap.Config.ARGB_4444, true);
}
else
{
mhandler.post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "null bitmap, sorry", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
}

Using custom class for JavaCameraView crashes the app

I am using OpenCV for android and i am trying to set a custom frame rate. Well right now i am trying to set the range for frame rate. I am also trying to set the custom resolution
I am following the openCV tutorial 3 Camera Control. the app is crashing as i start running it on my device. I am using Nexus 7 2013 tablet
Following is my code:
public class Tutorial2Activity extends Activity implements CvCameraViewListener2
{
private static final String TAG = "OCVSample::Activity";
private static final int VIEW_MODE_RGBA = 0;
private static final int VIEW_MODE_GRAY = 1;
private static final int VIEW_MODE_CANNY = 2;
private static final int VIEW_MODE_FEATURES = 5;
private int mViewMode;
private Mat mRgba;
private Mat mIntermediateMat;
private Mat mGray;
private MenuItem mItemPreviewRGBA;
private MenuItem mItemPreviewGray;
private MenuItem mItemPreviewCanny;
private MenuItem mItemPreviewFeatures;
private CustomizeCameraView mOpenCvCameraView;
private List<Size> mResolutionList;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("mixed_sample");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public Tutorial2Activity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.tutorial2_surface_view);
mOpenCvCameraView = (CustomizeCameraView) findViewById(R.id.tutorial2_activity_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "called onCreateOptionsMenu");
mItemPreviewRGBA = menu.add("Preview RGBA");
mItemPreviewGray = menu.add("Preview GRAY");
mItemPreviewCanny = menu.add("Canny");
mItemPreviewFeatures = menu.add("Find features");
return true;
}
#Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
mIntermediateMat = new Mat(height, width, CvType.CV_8UC4);
mGray = new Mat(height, width, CvType.CV_8UC1);
mResolutionList = mOpenCvCameraView.getResolutionList();
int mFrameWidth = (int) mResolutionList.get(7).width;
int mFrameHeight = (int) mResolutionList.get(7).height;
mOpenCvCameraView.setResolution(mFrameHeight,mFrameWidth);
//mOpenCvCameraView.setPreviewFPS(1000, 31000);
}
public void onCameraViewStopped() {
mRgba.release();
mGray.release();
mIntermediateMat.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
return inputFrame.rgba();
}
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item == mItemPreviewRGBA) {
mViewMode = VIEW_MODE_RGBA;
} else if (item == mItemPreviewGray) {
mViewMode = VIEW_MODE_GRAY;
} else if (item == mItemPreviewCanny) {
mViewMode = VIEW_MODE_CANNY;
} else if (item == mItemPreviewFeatures) {
mViewMode = VIEW_MODE_FEATURES;
}
return true;
}
public native void FindFeatures(long matAddrGr, long matAddrRgba);
}
And the JavaCameraView custom class
public class CustomizeCameraView extends JavaCameraView{
public CustomizeCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//#SuppressWarnings("deprecation")
public void setPreviewFPS(double min, double max){
Camera.Parameters params = mCamera.getParameters();
params.setPreviewFpsRange((int)(min*1000), (int)(max*1000));
//params.setPreviewFrameRate(min);
mCamera.setParameters(params);
// mCamera.getSupportedPreviewFpsRange();
}
public List<Size> getResolutionList() {
return mCamera.getParameters().getSupportedPreviewSizes();
// return mCamera.getParameters().getPictureSize();
}
public void setResolution(int h,int w){
Camera.Parameters params = mCamera.getParameters();
params.setPreviewSize(mFrameWidth, mFrameHeight);
mCamera.setParameters(params); // mCamera is a Camera object
}
public Size getResolution() {
return mCamera.getParameters().getPreviewSize();
}
}
and the logcat output is as follows:
05-23 14:27:18.192: E/AndroidRuntime(29339): FATAL EXCEPTION: main
05-23 14:27:18.192: E/AndroidRuntime(29339): Process: org.opencv.samples.tutorial2, PID: 29339
05-23 14:27:18.192: E/AndroidRuntime(29339): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.opencv.samples.tutorial2/org.opencv.samples.tutorial2.Tutorial2Activity}: java.lang.ClassCastException: org.opencv.android.JavaCameraView cannot be cast to org.opencv.samples.tutorial2.CustomizeCameraView
I found the solution
the problem was with my layout file. i inserted the tag for video display for directly usage of JavaCameraView instead of using the inherited class from JavaCameraView
problem:
< org.opencv.JavaCameraView />
corrected:
< "package_name"."Class_name_that_you_inherited_from_JavaCameraView" />
i hope it helps others :)

How to make an android camera preview stay focused?

I am quite new to Android, thus the code is not from me since I use it only to learn.
The application I want to make has to show a camera preview. I have the preview of the camera on the surface, but it's not focused. As a work-around I made a runnable that calls auto-focus every 750ms.
I would like to know how I can make this better since whenever I call auto-focus the preview will blur until it's focused again.
Thank you for any help.
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class Draw extends Activity {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private boolean cameraConfigured = false;
private Handler handler = new Handler();;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.draw);
preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
final Runnable r = new Runnable() {
#Override
public void run() {
camera.autoFocus(autoFocusCallback);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 750);
}
private AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean autoFocusSuccess, Camera arg1) {
}
};
#Override
public void onResume() {
super.onResume();
camera = Camera.open();
startPreview();
}
#Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
private void initPreview(int width, int height) {
if (camera != null && previewHolder.getSurface() != null) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("KritzelKunst-surfaceCallback", "Exception in setPreviewDisplay()", t);
Toast.makeText(Draw.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}
private void startPreview() {
if (cameraConfigured && camera != null) {
camera.startPreview();
inPreview = true;
}
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
initPreview(width, height);
startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
}
Try adding
<uses-feature android:name="android.hardware.camera.autofocus" />
in your manifest.

Categories

Resources