Surfaceview lifecycle when power button is pressed

475 views
Skip to first unread message

neeraj goel

unread,
Dec 20, 2014, 5:30:02 AM12/20/14
to google-adm...@googlegroups.com
Please tell me about when surfaceview lifecycle when power button is pressed ?

Eric Leichtenschlag (Mobile Ads SDK Team)

unread,
Dec 22, 2014, 1:00:51 PM12/22/14
to google-adm...@googlegroups.com
Hello,

A SurfaceView is just a view, which lives inside of an Activity. When the power button is pressed, the entire activity gets paused. It'll be the same as the activity lifecycle.

Thanks,
Eric

neeraj goel

unread,
Dec 22, 2014, 2:33:42 PM12/22/14
to google-adm...@googlegroups.com
I have created a game. I am having problem when power button is pressed while app is running. When i unlock phone, app is there on screen. Music starts but nothing else happens. It seems like it is frozen/hanged. To continue from that stage, i have to press home button to minimise it and then maximise it to continue playing. Please help me to solve this flaw. 


------------------------------------------------- StartingPoint.java----------------------------------------- 
package com.example.neeraj.ball;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public class StartingPoint extends Activity{

private boolean showingMainMenu;
public static GamePanel gamePanel;
public static Sound sound;
private AdView mAdView;
public static InterstitialAd interstitial;
//private boolean powerPressed = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_starting_point);
showingMainMenu = true;
Game.gameStartedfromStartingPoint = true;
sound = new Sound(this);
sound.mpBack.start();
        mAdView = (AdView)findViewById(R.id.adBannerStartingPage);
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("780DFBF4B07844FF522D0E6D9893852A")
                .build();
        mAdView.loadAd(adRequest);
        
        interstitial = new InterstitialAd(this);
        String id = String.valueOf(R.string.id_adInterstitialGameOver);
        interstitial.setAdUnitId(id);
        interstitial.loadAd(adRequest);
        
}
public static void displayInterstitial() {
   if (interstitial.isLoaded()) {
     interstitial.show();
   }
}

@Override
public void onBackPressed() {
//sound.playStopBackGroundMusic();
if (!showingMainMenu) {
showingMainMenu = true;
// Stop game loop
gamePanel.surfaceDestroyed(null);
setContentView(R.layout.activity_starting_point);
} else {
// Quitbkjkjbk
super.onBackPressed();
}
}

// Start game on click
public void onClickStartGame(View v) {
showingMainMenu = false;
gamePanel = new GamePanel(this);
setContentView(gamePanel);
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
if (mAdView != null) {
            mAdView.pause();
        }
sound.mpBack.stop();
try {
sound.mpBack.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(gamePanel != null)
gamePanel.pause();
super.onPause();
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (mAdView != null) {
            mAdView.resume();
        }
sound.mpBack.start();
if(gamePanel != null)
gamePanel.resume();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (mAdView != null) {
            mAdView.destroy();
        }
super.onDestroy();
}
}
--------------------------------------------------------------GamePanel.java
package com.example.neeraj.ball;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

@SuppressLint("ClickableViewAccessibility") 
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private Game game;
public GameLoopThread gameLoopThread;
private Context context;
public GamePanel(Context context) {
super(context);
this.context = context;
this.setFocusable(true);
this.getHolder().addCallback(this);
}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}

public void surfaceCreated(SurfaceHolder holder) {
// We can now safely start the game loop.
startGame();
}
private void startGame(){
if(game == null)
game = new Game(getWidth(), getHeight(), getResources(), context);
gameLoopThread = new GameLoopThread(this.getHolder(), game);
gameLoopThread.running = true;
gameLoopThread.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
Game.pausePressed = true;
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
game.touchEvent_actionDown(event, event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
game.touchEvent_actionMove(event, event.getX(), event.getY());
break;
case MotionEvent.ACTION_UP:
game.touchEvent_actionUp(event);
break;
}
return true;
}

public void pause(){
Game.pausePressed = true;
gameLoopThread.running = false;
}
public void resume(){
}

}
--------------------------- GameLoopThread.java----------------------------
package com.example.neeraj.ball;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class GameLoopThread extends Thread {
private final static int MAX_FPS = 30;           // How many times per second the game should be updated, drawn?
private final static int MAX_FRAME_SKIPS = 5; // Maximum number of frames to be skipped
private final static int FRAME_PERIOD = 1000 / MAX_FPS; // The frame period
// Surface holder that can access the physical surface.
private SurfaceHolder surfaceHolder;
private Game game;
// Elapsed game time in milliseconds.
private long gameTime;

// Holds the state of the game loop.
public boolean running = false;

public GameLoopThread(SurfaceHolder surfaceHolder, Game game) {
super();

this.surfaceHolder = surfaceHolder;
this.game = game;
this.gameTime = 0;
}

@Override
public void run() {
Canvas canvas;
long beginTime; // the time when the cycle begun
long timeDiff; // the time it took for the cycle to execute
int sleepTime; // ms to sleep (<0 if we're behind)
int framesSkipped; // number of frames being skipped 

sleepTime = 0;
while(running){
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas(); // Try locking the canvas for exclusive pixel editing in the surface.
synchronized(surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0; // Resetting the frames skipped.
this.game.Update(this.gameTime);
this.game.Draw(canvas);
// Calculate how long did the cycle take.
timeDiff = System.currentTimeMillis() - beginTime;
// Calculate sleep time.
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
try {
// Send the thread to sleep for a short period.
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS && !game.gameOver) {
// We need to catch up, so we update without drawing the game to the screen.
this.game.Update(this.gameTime);
sleepTime += FRAME_PERIOD; // Add FRAME_PERIOD to check while condition again.
framesSkipped++;
}
this.gameTime += System.currentTimeMillis() - beginTime;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
// In case of an exception the surface is not left in an inconsistent state.
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}

}
---------------------------------- Game.java-----------------------------
package com.example.neeraj.ball;

import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.MotionEvent;

public class Game{

int limitOfIncresingSpeed;
public static boolean gameStartedfromStartingPoint = false;
Random r = new Random();
int noCollision = 0, prevCollision = 0;
public int highScore ;
public int id;
SharedPreferences sp;
SharedPreferences.Editor editor;
int ourColor[] = {Color.rgb(0, 0, 0)};
int lengthColorArray;
float racquetWidthFactor;
boolean firstUpdate;
private int count=0, time =3;
private Sound sound;
public static Resources res;
private int x, y, radius;
Bitmap wall, ball;
Paint paint, rectPaint, scoreDisplay, instruction, racquetPaint;
Typeface font;
static Context context;
Rect rect, racquet, ballRect, healthRect;
int xa, ya, constant;
int rx, ry, rwidth, rheight, tempR1;
public static boolean pausePressed = false;
Bitmap pause;
int pauseWidth;
int pauseX, pauseY;

Bitmap health; // health
int healthWidth;
int healthX, healthY, healthSpeed;
boolean healthDrawn;
public static int screenWidth;
public static int screenHeight;
public static float screenDensity;

private int score = 0;
String displayingScore = "";
public boolean gameOver = false;

public Game(int screenWidth, int screenHeight, Resources resources,
Context context1) {
Game.screenWidth = screenWidth;
Game.screenHeight = screenHeight;
Game.screenDensity = resources.getDisplayMetrics().density;
context = context1;
this.LoadContent(resources);
this.ResetGame();

}

private void LoadContent(Resources resources) {
res = resources;
wall = BitmapFactory.decodeResource(res, R.drawable.beach1);
ball = BitmapFactory.decodeResource(res, R.drawable.ball);
pause = BitmapFactory.decodeResource(res, R.drawable.pause);
health = BitmapFactory.decodeResource(res, R.drawable.health);
font = Typeface.createFromAsset(context.getAssets(),
"DK Downward Fall.ttf");
sound  = new Sound(context);
}
private void ResetGame() {
limitOfIncresingSpeed = 16;
healthWidth = (int)(screenWidth * 0.11);
health = Bitmap.createScaledBitmap(health, healthWidth, healthWidth, true);
healthX = r.nextInt(screenWidth - healthWidth - 20) + 10;
healthY = 0;
healthSpeed = 10;
healthDrawn = false;
pauseWidth = (int)(screenWidth * 0.10);
pause = Bitmap.createScaledBitmap(pause, pauseWidth, pauseWidth, true);
pauseX = screenWidth - pauseWidth;
pauseY = 5;
lengthColorArray = ourColor.length;
noCollision = prevCollision = 0;
sp = context.getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
highScore = sp.getInt("your_int_key", 0);
time = 3;
firstUpdate = true;
x = y = score = count = 0;
radius = (int)(screenWidth/13);
ball = Bitmap.createScaledBitmap(ball, radius , radius, true);
radius = ball.getWidth();
paint = new Paint();
paint.setColor(ourColor[r.nextInt(lengthColorArray)]);

rectPaint = new Paint();
rectPaint.setColor(Color.argb(10, 255, 66, 99));

scoreDisplay = new Paint();
scoreDisplay.setColor(Color.argb(150, 0, 0, 0));
scoreDisplay.setTypeface(font);
scoreDisplay.setTextSize((float) (Game.screenHeight * 0.05));

instruction = new Paint();
instruction.setColor(Color.argb(100, 256, 256, 256));
instruction.setTypeface(font);
instruction.setTextSize((float) (Game.screenHeight * 0.05));
instruction.setTextAlign(Align.CENTER);

racquet = new Rect(rx, ry, rx + rwidth, ry + rheight);
racquetPaint = new Paint();
racquetPaint.setColor(ourColor[r.nextInt(lengthColorArray)]);

rwidth = (int) (Game.screenWidth * 0.3);
racquetWidthFactor = 0.75f;
rheight = (int) (Game.screenHeight * 0.05);
racquetPaint = new Paint();
instruction.setColor(Color.argb(100, 0, 0, 0));
rx = (int) ((Game.screenWidth * 0.50) - (rwidth * 0.50));
ry = (int) (Game.screenHeight - rheight - Game.screenHeight * 0.15);
tempR1 = 5;

constant= 6;
xa = ya = constant;

score = 0;
gameOver = false;
x = r.nextInt(Game.screenWidth - 2 *radius);
}

public void Update(long gameTime) {
// moving the ball
if(firstUpdate){
gameStartedfromStartingPoint = false;
StartingPoint.sound.mpBack.start();
firstUpdate = false;
}
if(!pausePressed){
if(time <= 0){
checkScore();
collisionHealthRac();
updateHealth();
if (x + xa + radius < 0)
xa = constant;
if (x + xa + radius > screenWidth - radius)
xa = -constant;
if (y + ya + radius< 0)
ya = constant;
if (y + ya + radius> (screenHeight * 0.85) - radius) {
gameOver = true;
if(count == 0){
StartingPoint.sound.mpBack.stop();
try {
StartingPoint.sound.mpBack.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound.playGameOverSound();
count++;
}
}
else{
// collision detection
ballRect = new Rect(x + xa, y + ya, x + xa + 2*radius, y + ya + 2*radius);
if (collisionRacBall()) {
noCollision ++;
paint.setColor(ourColor[r.nextInt(lengthColorArray)]);
racquetPaint.setColor(ourColor[r.nextInt(lengthColorArray)]);
increasingSpeedBall();
changingRacquetWidth();
sound.playClickSound();
score = score + 5;
ya = -constant;
//y = ry - 2 * radius;
}
x = x + xa;
y = y + ya;
}
}
}
}

private void checkScore() {
// TODO Auto-generated method stub
switch(score){
case 200:
limitOfIncresingSpeed++;
break;
case 300:
limitOfIncresingSpeed++;
break;
case 400:
limitOfIncresingSpeed++;
break;
case 500:
limitOfIncresingSpeed++;
break;
}
}

boolean collisionRacBall() {
if (racquet.intersect(ballRect))
return true;
else
return false;
}

private void collisionHealthRac() {
// TODO Auto-generated method stub
if(healthDrawn){
healthRect = new Rect(healthX, healthY , healthX + health.getWidth() , healthY + health.getHeight());
if (racquet.intersect(healthRect)){
rwidth *= 2;
if(rwidth > (int) (Game.screenWidth * 0.3))
rwidth = (int) (Game.screenWidth * 0.3);
constant /=2;
if(constant < 6)
constant = 6;
healthDrawn = false;
}
}
}

private void updateHealth() {
// TODO Auto-generated method stub
if(healthDrawn == false){
if(constant > limitOfIncresingSpeed && (noCollision - prevCollision >5)){
healthX = r.nextInt(screenWidth - healthWidth - 20) + 10;
healthY = 0;
healthDrawn = true;
prevCollision = noCollision;
}
}
else{
if (healthY < (screenHeight)) {
healthY += healthSpeed;
}
else{
healthDrawn = false;
healthY = 0;
}
}
}

private void changingRacquetWidth() {
// TODO Auto-generated method stub
if(noCollision %3 == 0){
rwidth = (int)(rwidth * racquetWidthFactor);
if(rwidth < screenWidth*0.20)
rwidth = (int)(screenWidth*0.20);
}
}

private void increasingSpeedBall() {
// TODO Auto-generated method stub
if(noCollision <= 5){
constant ++;
}
else if(noCollision % 3 == 0){
constant ++;
}
}

public void Draw(Canvas canvas) {
// First we need to erase everything we draw before.
if(pausePressed){ // if pause button is pressed
drawWallpaper(canvas);
drawBitmapBall(canvas);
drawRectInstruction(canvas);
drawRectRacquet(canvas);
drawTextScore(canvas);
drawTextBestScore(canvas);
drawTextInstruction(canvas);
drawPauseView(canvas);
}
else{ // resume
if(time > 0){
drawWallpaper(canvas);
drawPause(canvas);
drawBitmapBall(canvas);
drawRectInstruction(canvas);
drawRectRacquet(canvas);
drawTextScore(canvas);
drawTextBestScore(canvas);
drawTextInstruction(canvas);
drawTextStarting(canvas);
}
else{
if(!gameOver){ // actual game
drawWallpaper(canvas);
drawPause(canvas);
drawBitmapBall(canvas);
drawRectInstruction(canvas);
if(healthDrawn)
drawHealth(canvas);
drawRectRacquet(canvas);
drawTextScore(canvas);
drawTextBestScore(canvas);
drawTextInstruction(canvas);
}
else{
//saving highscore
if(score > this.highScore){
editor = sp.edit();
editor.putInt("your_int_key", score);
editor.commit();
}
drawGameOver(canvas);
}
}
}
}

private void drawHealth(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(health, healthX, healthY, null);
}

private void drawPause(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(pause, pauseX, pauseY, null);
}

private void drawPauseView(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(wall, 0, 0, null);
Paint output = new Paint();
output.setARGB(255, 0, 0, 0);
output.setTextAlign(Align.CENTER);
output.setTypeface(font);
output.setTextSize(screenWidth/7);
canvas.drawText("PAUSED", canvas.getWidth()/2, (float)(canvas.getHeight() * 0.350), output);
output.setTextSize(screenWidth/12);
canvas.drawText("Touch to Start Again", canvas.getWidth()/2, (float)(canvas.getHeight() * 0.70), output);
}

private void drawGameOver(Canvas canvas) {
// TODO Auto-generated method stub

canvas.drawBitmap(wall, 0, 0, null);
Paint output = new Paint();
output.setARGB(255, 0, 0, 0);
output.setTextAlign(Align.CENTER);
output.setTypeface(font);
output.setTextSize(screenWidth/8);
canvas.drawText("GAME OVER", canvas.getWidth()/2, (float)(canvas.getHeight() * 0.350), output);
String out = "SCORE : " + score;
output.setTextSize(screenWidth/6);
canvas.drawText(out, canvas.getWidth()/2, (float)(canvas.getHeight() * 0.70), output);
output.setTextSize(screenWidth/12);
canvas.drawText("Touch to Start Again", canvas.getWidth()/2, (float)(canvas.getHeight() * 0.85), output);
StartingPoint.displayInterstitial();
}

private void drawTextStarting(Canvas canvas) {
// TODO Auto-generated method stub
Paint starting = new Paint();
starting.setColor(Color.argb(150, 0, 0, 0));
starting.setTextSize((float)(screenWidth * 0.10));
starting.setTypeface(font);
starting.setTextAlign(Align.CENTER);
canvas.drawText("GAME STARTS IN", (float)(screenWidth * 0.50), (float)(screenHeight * 0.40 ), starting);
starting.setTextSize((float)(screenWidth * 0.30));
canvas.drawText(""+time, (float)(screenWidth * 0.50), (float)(screenHeight * 0.750 ), starting);
time --;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private void drawTextInstruction(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawText("Swipe finger here",
(float) (canvas.getWidth() * 0.50),
(float) (canvas.getHeight() * 0.93), instruction);
}

private void drawTextBestScore(Canvas canvas) {
// TODO Auto-generated method stub
displayingScore = "BEST SCORE : " + this.highScore; // best score
canvas.drawText(displayingScore, (float) (canvas.getWidth() * 0.02),
(float) (canvas.getHeight() * 0.13), scoreDisplay);
}

private void drawTextScore(Canvas canvas) {
// TODO Auto-generated method stub
displayingScore = "SCORE : " + score; // current score
canvas.drawText(displayingScore, (float) (canvas.getWidth() * 0.02),
(float) (canvas.getHeight() * 0.07), scoreDisplay);
}

private void drawRectRacquet(Canvas canvas) {
// TODO Auto-generated method stub
racquet = new Rect(rx, ry, rx + rwidth, ry + rheight);
canvas.drawRect(racquet, racquetPaint);
}

private void drawRectInstruction(Canvas canvas) {
// TODO Auto-generated method stub
rect = new Rect(0, (int) (canvas.getHeight() * 0.85),
canvas.getWidth(), canvas.getHeight());
canvas.drawRect(rect, rectPaint);
}

private void drawBitmapBall(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(ball, x+radius, y+radius, null);
}

private void drawWallpaper(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(wall, 0, 0, null);
}

public void touchEvent_actionDown(MotionEvent event, float f, float g) {
if(gameOver){
this.ResetGame();
}
else if(pausePressed)
pausePressed = false;
else{
int x,y;
x = (int)(f);
y = (int)(g);
if( x >= pauseX && x <= screenWidth && y >= pauseY && y < (pauseY + pauseWidth)){ // touch on pause
pausePressed = true;
sound.playClickSound();
}
else{ // touch on rectangle below racquet
rx = (int) (f - rwidth / 2);
if (rx + rwidth > screenWidth)
rx = screenWidth - rwidth;
if (rx < 0)
rx = 0;
}
}
}

public void touchEvent_actionMove(MotionEvent event, float f, float g) {
rx = (int) (f - rwidth / 2);
if (rx + rwidth > screenWidth)
rx = screenWidth - rwidth;
if (rx < 0)
rx = 0;
}

public void touchEvent_actionUp(MotionEvent event) {

}

}

William Ferguson

unread,
Dec 22, 2014, 4:28:01 PM12/22/14
to google-adm...@googlegroups.com
This is really not a question for this list.
I suggest you narrow  down your problem a bit and then post on StackOveflow.
...
Reply all
Reply to author
Forward
0 new messages