Animations in Android - android
I'm new in Android and I want to do some animations. I'm trying to make my sprite sheet move automatically. But there is a problem with screen rendering. It leaves a trail while it is moving.Click here to see the screen shot
This is my code:
public class SampleAnimationActivity extends Activity {
/** Called when the activity is first created. */
Screen screen;
MapAnimation mapAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
screen = new Screen(this);
setContentView(screen);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public class Screen extends SurfaceView implements Callback{
private SurfaceHolder holder;
private MySurfaceViewThread mySurfaceViewThread;
private boolean isSurfaceCreated;
private Bitmap character, tiles;
public Screen(Context context) {
super(context);
initialize();
}
public void initialize(){
//Create a new SurfaceHolder and assign this class as its callback...
holder = getHolder();
holder.addCallback(this);
isSurfaceCreated = false;
character = BitmapFactory.decodeResource(getResources(),R.drawable.penguin_sprite);
tiles = BitmapFactory.decodeResource(getResources(), R.drawable.tile_sprites);
resume();
}
public void resume(){
//Create and start the graphics update thread.
if(mySurfaceViewThread == null){
mySurfaceViewThread = new MySurfaceViewThread();
if(isSurfaceCreated == true){
mySurfaceViewThread.start();
}
}
}
public void pause(){
//Kill the graphics update thread
if(mySurfaceViewThread != null){
mySurfaceViewThread.pause();
mySurfaceViewThread = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
isSurfaceCreated = true;
if(mySurfaceViewThread != null){
mySurfaceViewThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
isSurfaceCreated = false;
pause();
}
public class MySurfaceViewThread extends Thread{
private boolean isPaused;
private boolean characterLoaded, characterDrawn;
private SurfaceHolder surfaceHolder;
public MySurfaceViewThread(){
super();
isPaused = false;
characterLoaded = false;
surfaceHolder = holder;
characterDrawn = false;
}
public void run(){
//Repeat the drawing loop until the thread is stopped
while(!isPaused){
if(!surfaceHolder.getSurface().isValid()){
continue;
}
if(characterLoaded == false){
mapAnimation = new MapAnimation(screen, character);
characterLoaded = true;
}
Canvas canvas = surfaceHolder.lockCanvas();
mapAnimation.onDraw(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
}
public void onDraw(){
}
}
}
}
public class MapAnimation {
private Screen screen;
private Bitmap character;
private int width, height, xPosition, yPosition, xSpeed, ySpeed;
public MapAnimation(Screen screen, Bitmap character) {
this.screen = screen;
this.character = character;
this.width = character.getWidth();
this.height = character.getHeight();
xPosition = 0;
yPosition = 0;
xSpeed = 5;
ySpeed = 5;
}
public void updateCharacter(){
if(xPosition > screen.getWidth() - width - xSpeed){
xSpeed = 0;
ySpeed = 5;
}
if(yPosition > screen.getHeight() - height - ySpeed){
xSpeed = -5;
ySpeed = 0;
}
if(xPosition + xSpeed < 0){
xPosition=0;
xSpeed = 0;
ySpeed = -5;
}
if(yPosition+ySpeed < 0){
yPosition = 0;
xSpeed = 5;
ySpeed = 0;
}
xPosition += xSpeed;
yPosition += ySpeed;
}
public void onDraw(Canvas canvas){
updateCharacter();
Rect src = new Rect(0, 0,135,225);
Rect dst = new Rect(xPosition, yPosition, xPosition+width, yPosition+height);
canvas.drawBitmap(character, src, dst, null);
}
}
Your help will be deeply appreciated :)
I already solved my problem, I just need to add "drawColor(color.BLACk);" before calling mapAnimation.onDraw() method.
Related
Simple game works on tablet but sometimes lags on phone
I'm developing simple Android game, but I'm running into problems while testing it. When I run it on Lenovo Tab3 7 tablet (Android 5.0.1 ) or LG P880 phone (Android 4.0.3) it works fine. When I run it on Samsung S7 phone (Android 7.0) game usually runs fine. What I mean by this is that I can run it 10 times in a row with no problems, but sometimes game halts for 5-30 seconds or stops responding. This usually happens during starting of new Activity or very shortly after it. Game has 4 Activities which use extended SurfaceView as layout. All SurfaceViews implement Runnable. Activities are: Splash screen (noHistory = "true" in Manifest), Menu, Difficulty choice and Game. I use only mdpi drawables and scale them proportionally to all screen sizes. Bitmaps are loaded using BitmapFactory.decodeResource with BitmapFactory.Options inDensity = 1, inScaled = false. When the problem occurs logcat shows only garbage collection. Sometimes game "pauses" (no taps are registered) for 5-30 seconds and resumes normally, sometimes it has to be restarted due to no response. I feel like game stops collecting input for some reason. Input is handled by overriding onTouchEvent and checking if ACTION_UP is within tapped image bounds. As I said, this happens only on S7 (I tried it on two phones), not on tablet or P880, so I'm thinking it might be something to do with Nougat or me forcing lower density on the phone. So, since I'm running out of ideas what could be causing this and me being new to Android game development, does anyone know/have any idea where I should be looking for solution? Is there anything Nougat-specific I should be setting/checking? Does forcing pixel density affect device performance in any way? Edit 1 globalApp public class globalApp extends Application { SoundPool soundPool; SoundPool.Builder soundPoolBuilder; AudioAttributes audioAttributes; AudioAttributes.Builder audioAttributesBuilder; int soundTap, soundCorrect, soundIncorrect, soundVictory, soundDefeat; int soundBarrelVerySlow, soundBarrelSlow, soundBarrelNormal, soundBarrelFast, soundBarrelVeryFast; #Override public void onCreate() { super.onCreate(); } public void buildSoundPool(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { audioAttributesBuilder = new AudioAttributes.Builder(); audioAttributesBuilder.setUsage(AudioAttributes.USAGE_GAME); audioAttributesBuilder.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION); audioAttributes = audioAttributesBuilder.build(); soundPoolBuilder = new SoundPool.Builder(); soundPoolBuilder.setMaxStreams(2); soundPoolBuilder.setAudioAttributes(audioAttributes); soundPool = soundPoolBuilder.build(); } else { soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); } } public void loadSounds(){ soundBarrelVerySlow = soundPool.load(this,R.raw.very_slow_move, 1); soundBarrelSlow = soundPool.load(this, R.raw.slow_move, 1); soundBarrelNormal = soundPool.load(this, R.raw.slow_move, 1); soundBarrelFast = soundPool.load(this,R.raw.fast_move, 1); soundBarrelVeryFast = soundPool.load(this,R.raw.very_fast_move, 1); soundTap = soundPool.load(this, R.raw.tap_sound, 1); soundCorrect = soundPool.load(this, R.raw.correct, 1); soundIncorrect = soundPool.load(this, R.raw.incorrect, 1); soundVictory = soundPool.load(this, R.raw.victory, 1); soundDefeat = soundPool.load(this, R.raw.defeat, 1); } public void playTap(){ soundPool.play(soundTap, 1, 1,1, 0, 1); } public void playCorrect(){ soundPool.play(soundCorrect, 1, 1,1, 0, 1); } public void playIncorrect(){ soundPool.play(soundIncorrect, 1, 1,1, 0, 1); } public void playVictory(){ soundPool.play(soundVictory, 1, 1,1, 0, 1); } public void playDefeat(){ soundPool.play(soundDefeat, 1, 1,1, 0, 1); } public void playBarrelVerySlow(){soundPool.play(soundBarrelVerySlow, 1, 1, 1, 0, 1);} public void playBarrelSlow(){soundPool.play(soundBarrelSlow, 1, 1, 1, 0, 1);} public void playBarrelNormal(){ soundPool.play(soundBarrelNormal, 1, 1,1, 0, 1); } public void playBarrelFast(){soundPool.play(soundBarrelFast, 1, 1, 1, 0, 1);} public void playBarrelVeryFast(){soundPool.play(soundBarrelVeryFast, 1, 1, 1, 0, 1);} } MenuItem public class MenuItem { private Bitmap bmp; private Context context; private Rect sourceRect; private RectF destRect; private int srcWidth; private int srcHeight; private int destW, destH; private int x, y; private int screenH; public MenuItem(Context ctx, String bmpName, int w, int x, int y, int sX, int sY){ context = ctx; BitmapFactory.Options bmpFOptions = new BitmapFactory.Options(); bmpFOptions.inDensity = 1; bmpFOptions.inScaled = false; int res = context.getResources().getIdentifier(bmpName, "drawable", ctx.getPackageName()); bmp = BitmapFactory.decodeResource(ctx.getResources(), res, bmpFOptions); srcWidth = w; srcHeight = bmp.getHeight(); this.x = x; this.y = y; screenH = sY; sourceRect = new Rect(0,0, srcWidth, srcHeight); destRect = new RectF(); setProportionalDestinationRect(sX, sY); } private void setProportionalDestinationRect(int scrX, int scrY) { if (scrX != 1024 || scrY != 552){ float propX = (float)scrX/1024; float propY = (float)scrY/600; // All drawables are designed for 1024x600 screen // if device screen is different, scale image proportionally destW = (int)(srcWidth * propX); destH = (int) (srcHeight * propY); x = (int) (x*propX); y = (int) (y*propY); } else { destW = srcWidth; destH = srcHeight; } destRect.set(x,y, x+destW,y+destH); } public void update(){ } public Bitmap getBmp() { return bmp; } public void setBmp(Bitmap bmp) { this.bmp = bmp; } public Rect getSourceRect() { return sourceRect; } public void setSourceRect(Rect sourceRect) { this.sourceRect = sourceRect; } public RectF getDestRect() { return destRect; } public void setDestRect(RectF destRect) { this.destRect = destRect; } public boolean contains(int x, int y){ if (destRect.left <= x && destRect.right >= x) if (destRect.top <= y && destRect.bottom >= y) return true; return false; } public void setY(int y) { this.y = y; if (screenH != 552){ float propY = (float)screenH/600; y = (int) (y*propY); } destRect.set(x,y, x+destW,y+destH); } } MainActivity public class MainActivity extends Activity { private boolean backPressedOnce = false; long backPressedTime = 0; private MainActivitySurface mainActivitySurface; globalApp app; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Setting full screen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); int x = getIntent().getIntExtra("screenWidth", 500); int y = getIntent().getIntExtra("screenHeight", 500); app = (globalApp) getApplication(); app.buildSoundPool(); app.loadSounds(); mainActivitySurface = new MainActivitySurface(this, app, x, y); mainActivitySurface.setParentActivity(MainActivity.this); setContentView(mainActivitySurface); } #Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1001) { if (resultCode == RESULT_OK) { int result = data.getIntExtra("difficulty", 3); mainActivitySurface.setResultDifficulty(result); } } } #Override protected void onPause() { super.onPause(); mainActivitySurface.pause(); } #Override protected void onResume() { super.onResume(); backPressedOnce = false; mainActivitySurface.resume(); } #Override public void onBackPressed() { if (backPressedOnce && backPressedTime + 2000 > System.currentTimeMillis()) { Process.killProcess(Process.myPid()); System.exit(1); } else { Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show(); backPressedOnce = true; } backPressedTime = System.currentTimeMillis(); } } MainActivitySurface public class MainActivitySurface extends SurfaceView implements Runnable { private Context context; private SurfaceHolder surfaceHolder; private Canvas canvas; private Thread thread = null; volatile private boolean running = false; private boolean surfaceCreated = false; private Intent playIntent; private Intent difficultyIntent; // Screen size private int screenWidth, screenHeight; //Menu items private MenuItem menuItemPlay, menuItemDifficulty, middleBarrel, bg; private int difficulty = 3; private Activity parentActivity; private globalApp app; public MainActivitySurface(Context ctx, globalApp a, int scrW, int scrH){ super(ctx); context = ctx; screenHeight = scrH; screenWidth = scrW; app = a; surfaceHolder = getHolder(); surfaceHolder.addCallback(new SurfaceHolder.Callback() { #Override public void surfaceCreated(SurfaceHolder holder) { surfaceCreated = true; } #Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } #Override public void surfaceDestroyed(SurfaceHolder holder) { } }); bg = new MenuItem(context, "main_activity_background_single", 1024, 0, 0, scrW, scrH); menuItemPlay = new MenuItem(context, "menu_item_play_single", 233,(1024-233)/2,100, scrW, scrH); menuItemDifficulty = new MenuItem(ctx, "menu_item_difficulty_single", 520,(1024 - 520)/2,400,scrW,scrH); middleBarrel = new MenuItem(ctx, "middle_barrel_single", 323,(1024-323)/2,200,scrW,scrH); playIntent = new Intent(context, GameActivity.class); playIntent.putExtra("screenWidth", screenWidth); playIntent.putExtra("screenHeight", screenHeight); } #Override public void run() { while (running){ draw(); } } private void draw() { if(surfaceHolder.getSurface().isValid()){ canvas = surfaceHolder.lockCanvas(); canvas.drawBitmap(bg.getBmp(), bg.getSourceRect(), bg.getDestRect(), null); canvas.drawBitmap(menuItemPlay.getBmp(), menuItemPlay.getSourceRect(), menuItemPlay.getDestRect(), null); canvas.drawBitmap(menuItemDifficulty.getBmp(), menuItemDifficulty.getSourceRect(), menuItemDifficulty.getDestRect(), null); canvas.drawBitmap(middleBarrel.getBmp(), middleBarrel.getSourceRect(), middleBarrel.getDestRect(), null); surfaceHolder.unlockCanvasAndPost(canvas); } } public void resume(){ running = true; thread = new Thread(this); thread.start(); } public void pause(){ running = false; boolean retry = false; while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { e.printStackTrace(); Log.d("info", "MainActivitySurface: Error joining thread"); } } } #Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & event.ACTION_MASK){ case MotionEvent.ACTION_UP: if (menuItemPlay.contains((int) event.getX(), (int) event.getY())){ app.playTap(); parentActivity.startActivity(playIntent); parentActivity.overridePendingTransition(0,0); break; } if (menuItemDifficulty.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficultyIntent = new Intent(parentActivity, DifficultyActivity.class); difficultyIntent.putExtra("screenWidth", screenWidth); difficultyIntent.putExtra("screenHeight", screenHeight); difficultyIntent.putExtra("difficulty", difficulty); parentActivity.startActivityForResult(difficultyIntent, 1001); parentActivity.overridePendingTransition(0, 0); break; } } return true; } public void setParentActivity(Activity act){ parentActivity = act; } public void setResultDifficulty(int diff){ difficulty = diff; playIntent.putExtra("difficulty", difficulty); } } DifficultyActivity public class DifficultyActivity extends Activity { private DifficultySurface surface; private globalApp app; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Setting full screen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); app = (globalApp) getApplication(); surface = new DifficultySurface(this, app, getIntent().getIntExtra("screenWidth", 500), getIntent().getIntExtra("screenHeight", 500)); setContentView(surface); } #Override protected void onPause() { super.onPause(); app.soundPool.release(); surface.pause(); overridePendingTransition(0, 0); } #Override protected void onResume() { super.onResume(); app.buildSoundPool(); app.loadSounds(); surface.resume(); } } DifficultySurface public class DifficultySurface extends SurfaceView implements Runnable { private SurfaceHolder surfaceHolder; private Thread thread = null; private Canvas canvas; private Context context; private globalApp app; private boolean surfaceCreated = false; private boolean running = false; private MenuItem bgProp, arrowBarrel, okButton, diffVeryEasy, diffEasy, diffNormal, diffHard, diffVeryHard; private int difficulty; public DifficultySurface(Context ctx, globalApp a, int scrW, int scrH){ super(ctx); context = ctx; app = a; surfaceHolder = getHolder(); surfaceHolder.addCallback(new SurfaceHolder.Callback() { #Override public void surfaceCreated(SurfaceHolder holder) { surfaceCreated = true; } #Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } #Override public void surfaceDestroyed(SurfaceHolder holder) { } }); difficulty = ((Activity)context).getIntent().getIntExtra("difficulty", 3); bgProp = new MenuItem(ctx, "difficulty_background", 1024, 0, 0, scrW, scrH); diffVeryEasy = new MenuItem(ctx, "very_easy",796, 100, 100, scrW, scrH); diffEasy = new MenuItem(ctx, "easy",796, 100, 200 , scrW, scrH); diffNormal = new MenuItem(ctx, "normal",796, 100, 300, scrW, scrH); diffHard = new MenuItem(ctx, "hard",796, 100, 400 , scrW, scrH); diffVeryHard = new MenuItem(ctx, "very_hard",796, 100, 500, scrW, scrH); okButton = new MenuItem(ctx, "ok_button", 100, 924, 500, scrW, scrH); arrowBarrel = new MenuItem(ctx, "barrel_arrow", 100, 0, 100*difficulty, scrW, scrH); } #Override public void run() { while (running) { if (surfaceCreated) { update(); draw(); } } } private void update() { arrowBarrel.setY(difficulty*100); } private void draw() { if (surfaceHolder.getSurface().isValid()){ canvas = surfaceHolder.lockCanvas(); canvas.drawBitmap(bgProp.getBmp(), bgProp.getSourceRect(), bgProp.getDestRect(), null); canvas.drawBitmap(arrowBarrel.getBmp(), arrowBarrel.getSourceRect(), arrowBarrel.getDestRect(), null); canvas.drawBitmap(diffVeryEasy.getBmp(), diffVeryEasy.getSourceRect(), diffVeryEasy.getDestRect(), null); canvas.drawBitmap(diffEasy.getBmp(), diffEasy.getSourceRect(), diffEasy.getDestRect(), null); canvas.drawBitmap(diffNormal.getBmp(), diffNormal.getSourceRect(), diffNormal.getDestRect(), null); canvas.drawBitmap(diffHard.getBmp(), diffHard.getSourceRect(), diffHard.getDestRect(), null); canvas.drawBitmap(diffVeryHard.getBmp(), diffVeryHard.getSourceRect(), diffVeryHard.getDestRect(), null); canvas.drawBitmap(okButton.getBmp(), okButton.getSourceRect(), okButton.getDestRect(), null); surfaceHolder.unlockCanvasAndPost(canvas); } } #Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & event.ACTION_MASK){ case MotionEvent.ACTION_UP:{ if (diffVeryEasy.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficulty = 1; } if (diffEasy.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficulty = 2; } if (diffNormal.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficulty = 3; } if (diffHard.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficulty = 4; } if (diffVeryHard.contains((int) event.getX(), (int) event.getY())){ app.playTap(); difficulty = 5; } if (okButton.contains((int)event.getX(), (int) event.getY())){ app.playTap(); ((Activity)context).getIntent().putExtra("difficulty", difficulty); ((Activity)context).setResult(Activity.RESULT_OK, ((Activity)context).getIntent()); ((Activity)context).finish(); ((Activity)context).overridePendingTransition(0, 0); } break; } } return true; } public void pause(){ running = false; boolean retry = true; while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { e.printStackTrace(); } } ((Activity)context).overridePendingTransition(0, 0); } public void resume(){ running = true; thread = new Thread(this); thread.start(); } } GameActivity public class GameActivity extends Activity { private GameSurface surface; private globalApp app; private int difficulty; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Setting full screen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); difficulty = getIntent().getIntExtra("difficulty", 3); app = (globalApp) getApplication(); surface = new GameSurface(this, app, getIntent().getIntExtra("screenWidth", 500), getIntent().getIntExtra("screenHeight", 500), difficulty); surface.setParentActivity(this); setContentView(surface); } #Override protected void onPause() { super.onPause(); app.soundPool.release(); surface.pause(); } #Override protected void onPostResume() { super.onPostResume(); app.buildSoundPool(); app.loadSounds(); surface.resume(); } #Override protected void onStop() { super.onStop(); surface.stop(); } #Override public void onBackPressed() { super.onBackPressed(); finish(); } } Game halting happens either when I start DificultyActivity (I tap one MenuItem objects but nothing happens) or when I start GameActivity (game still shows MainActivity + MainActivitySurface). Android Monitor show less than 40MB of allocated memory, so bitmaps shouldn't be the problem in my opinion. I tried recycling all bitmaps but the problem was present (that's why I opted to use only mdpi drawables; at first I used all pixel densities but tried lowering resources in case that was causing halts).
It is hard to find the problem without looking at the code. There's nothing nougat-specific way of handling the resources. But android N claims to have a better memory management and since you are complaining a lot of garbage collections, it may be one of the cause. Make sure to recycle the unused bitmaps. And use RGB_565 as the preferred bitmap config which requires half memory than RGB_8888.
I have solved my problem. After posting question I came across this. It seems we had the same problem. When I slowed down drawing speed (using thread.sleep) there were no more issues. Thanks to those who helped me.
Android - Implement security in WallpaperService
I am using the WallpaperService class to set a live wallpaper on the device. I want to implement security on the system screen (to prevent screenshot or recording) where the 'Set Wallpaper' button shows up by the android system. So far, I have found one method of SurfaceView class - surfaceview.setSecure(boolean value) But, I am not able to get the instance of the SurfaceView inside my class. Please suggest some workaround to get the instance of this class. My Code- public class LiveWallpaperService extends WallpaperService { private int mDeviceWidth, mDeviceHeight; private int mAnimationWidth, mAnimationHeight; #Override public Engine onCreateEngine() { Movie movie = null; // Some Code here return new GIFWallpaperEngine(movie); } private class GIFWallpaperEngine extends Engine { private final int frameDuration = 24; private SurfaceHolder holder; private final Movie movie; private boolean visible; private final Handler handler; private final Runnable drawGIF = new Runnable() { public void run() { draw(); } }; public SurfaceView getSurfaceView(){ // How to find the SurfaceView object here? } GIFWallpaperEngine(Movie movie) { this.movie = movie; handler = new Handler(); } #Override public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); this.holder = surfaceHolder; } #Override public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { super.onSurfaceChanged(holder, format, width, height); mDeviceWidth = width; mDeviceHeight = height; } private void draw() { if (movie != null) { try { if (visible) { Canvas canvas = holder.lockCanvas(); canvas.save(); final float scaleFactorX = mDeviceWidth / (mAnimationWidth * 1.f); //608 is image width final float scaleFactorY = mDeviceHeight / (mAnimationHeight * 1.f); // Adjust size and position to fit animation on the screen canvas.scale(scaleFactorX, scaleFactorY); // w,h Size of displaying Item movie.draw(canvas, 0, 0); // position on x,y canvas.restore(); holder.unlockCanvasAndPost(canvas); movie.setTime((int) (System.currentTimeMillis() % movie.duration())); handler.removeCallbacks(drawGIF); handler.postDelayed(drawGIF, frameDuration); } } catch (Exception ex) { ex.printStackTrace(); } } } #Override public void onVisibilityChanged(boolean visible) { this.visible = visible; if (visible) { handler.post(drawGIF); } else { handler.removeCallbacks(drawGIF); } } #Override public void onDestroy() { super.onDestroy(); handler.removeCallbacks(drawGIF); } } }
Android app crashes upon attempt to switch to a different Activity
I am running into an issue in my app. When my game ends (when life == 0) I am attempting to switch to a game over screen by using a different activity. When the game ends, the app simply crashes. I have included the XML for the activity I am trying to switch from as well as indicating where the app crashes. If anyone could help out, that would be great! Thanks. activity_game.XML: SurfaceView I am trying to switch from once game ends: public class SVGameView extends SurfaceView implements Runnable { private SurfaceHolder holder; Thread thread = null; volatile boolean running = false; static final long FPS = 30; private Sprite sprite; private long lastClick; private Bitmap ball, gameOver; //private int x = 200, y = 200; private int scorePosX = 100; private int scorePosY = 100; private int countScore = 0; private int life = 1; public SVGameView(Context context) { super(context); thread = new Thread(this); holder = getHolder(); holder.addCallback(new SurfaceHolder.Callback() { #Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; running = false; while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { } } } #Override public void surfaceCreated(SurfaceHolder holder) { running = true; thread.start(); } #Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball2); gameOver = BitmapFactory.decodeResource(getResources(),R.drawable.endscreen); sprite = new Sprite(this, ball); } #Override public void run() { long ticksPS = 1000 / FPS; long startTime; long sleepTime; while (running) { Canvas c = null; startTime = System.currentTimeMillis(); try { c = getHolder().lockCanvas(); synchronized (getHolder()) { update(); draw(c); } } finally { if (c != null) { getHolder().unlockCanvasAndPost(c); } } sleepTime = ticksPS-(System.currentTimeMillis() - startTime); try { if (sleepTime > 0) thread.sleep(sleepTime); else thread.sleep(10); } catch (Exception e) {} } } private void update(){ sprite.update(); } #Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); Paint paint = new Paint(); canvas.drawPaint(paint); paint.setColor(Color.WHITE); paint.setTextSize(48); canvas.drawText("Score: " + countScore, scorePosX, scorePosY, paint); canvas.drawText("Lives: " + life, 500, 100, paint); sprite.onDraw(canvas); //Crashes here if(life == 0) { getContext().startActivity(new Intent(getContext(), SVGameOver.class)); } } #Override public boolean onTouchEvent(MotionEvent event) { if(System.currentTimeMillis()-lastClick > 300){ lastClick = System.currentTimeMillis(); } synchronized (getHolder()){ if(sprite.isHit(event.getX(), event.getY())){ countScore += 1; sprite.increase(); }else{ life --; } } return super.onTouchEvent(event); } } Activity I am trying to reach once the game ends: public class SVGameOver extends Activity { private Bitmap gameOverScreen; #Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); gameOverScreen = BitmapFactory.decodeResource(getResources(), R.drawable.endscreen); } protected void onDraw(Canvas canvas){ canvas.drawBitmap(gameOverScreen, 0,0,null); } }
I think logcat is asking you the right question: "have you declared this activity in your AndroidManifest.xml" ? If you think you did it, It's highly probable you did it in a wrong way, most of the times that you think you added an Activity to the manifest but you are receiving this kind of crash, 99,9% of the time you declared it with a wrong namespace
Declare SVGameOver activity in your AndroidManifest.xml: <activity android:name="com.example.welcome.assignment2.SVGameOver"> ... </activity>
How to insert a .png background in SurfaceView?
I'm current creating a game and i've made 3 main classes - GameView (which extends surfaceview), GameViewThread (which is a thread used for surfaceview) and a MainActivity. I want to enter a background image in SurfaceView, but have not been able to figure out how to do so. Using setBackground() in the onDraw method of GameView doesn't work as well. I would greatly appreciate any help you guys can provide me with. Here is my GameView class: public class GameView extends SurfaceView implements SurfaceHolder.Callback { private Bitmap bmp1; private SurfaceHolder holder; private GameLoopThread gameLoopThread; private Sprite sprite; private float sensorX = 0; private Platform platform[] = new Platform[7]; private Bonus GravUp[] = new Bonus[3]; private Bonus GravDown[] = new Bonus[3]; private Bitmap bmp2; private Bitmap bmp3; private boolean collision; private int a; private int b; private int c1; private double c2; int agility = 50; private Bitmap bmp4; public double getsensorX() { return sensorX; } public double setsensorX(float s) { return sensorX = s; } synchronized public int getSpriteY() { return sprite.y; } synchronized public int getSpriteX() { return sprite.x; } synchronized public int getSpriteHeight() { return sprite.height; } synchronized public int getSpriteWidth() { return sprite.width; } public GameView(Context context) { super(context); gameLoopThread = new GameLoopThread(this); holder = getHolder(); holder.addCallback(this); bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.russel); sprite = new Sprite(this); sprite.getBMP(bmp1); bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.brick); bmp3 = BitmapFactory.decodeResource(getResources(), R.drawable.gravup); bmp4 = BitmapFactory.decodeResource(getResources(), R.drawable.gravdown); for (int i = 0; i < GravUp.length; i++) { GravUp[i] = new Bonus(this, bmp3); } for (int i = 0; i < GravDown.length; i++) { GravDown[i] = new Bonus(this, bmp4); } for (int i = 0; i < platform.length; i++) { Random r = new Random(); platform[i] = new Platform(this, bmp2, 850 + 200 * i, 400 - r.nextInt(250)); } } #Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; gameLoopThread.setRunning(false); while (retry) { try { gameLoopThread.join(); retry = false; } catch (InterruptedException e) { } } } #Override public void surfaceCreated(SurfaceHolder holder) { gameLoopThread.setRunning(true); gameLoopThread.start(); } #Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } #Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.YELLOW); sprite.Draw(canvas); for (int i = 0; i < platform.length; i++) { platform[i].Draw(canvas); } for (int i = 0; i < GravUp.length; i++) { GravUp[i].Draw(canvas); } for (int i = 0; i < GravDown.length; i++) { GravDown[i].Draw(canvas); } } My MainActivity Class: public class MainActivity extends Activity { GameView gameView; FrameLayout game; RelativeLayout GameButtons; Button butOne; Button butTwo; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gameView = new GameView(this); game = new FrameLayout(this); GameButtons = new RelativeLayout(this); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); GameButtons.setLayoutParams(params); game.addView(gameView); game.addView(GameButtons); setContentView(game); } } How can I use an image I have saved in res/drawable-hdpi folder as the background to my game? Should I use the command in GameView or MainActivity? Do let me know if you need more information in order to help me out! Thank you
Move SurfaceView in Android
I'm developing a simple game like BSD robots. This game contains a rather large board (over 40 cells) and it doesn't look nice even at 10 inch tablet. My decision was to scroll (move) surface view and not to scale each figure which size is like finger spot. I've read tons articles about surface view but I cannot understand how to move it? My activity code: package ru.onyanov.robots; public class MainActivity extends Activity { public BoardView board; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); board = new BoardView(this); setContentView(board); } } Class Board: package ru.onyanov.robots; public class BoardView extends SurfaceView { private GameThread mThread; private boolean running = false; public final int sizeX = 50; public final int sizeY = 35; public final int cellSize = 64; private int robotCount = 4; public ArrayList<Cell> cells = new ArrayList<Cell>(); private ArrayList<Robot> robots = new ArrayList<Robot>(); private Hero hero; public Bitmap imageCell; public Bitmap imageRobot; public Bitmap imageHero; public BoardView(Context context) { super(context); makeGraphic(); constructCells(); constructRobots(); hero = new Hero(this, 3, 2, imageHero); mThread = new GameThread(this); getHolder().addCallback(new SurfaceHolder.Callback() { public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; mThread.setRunning(false); while (retry) { try { mThread.join(); retry = false; } catch (InterruptedException e) { } } } public void surfaceCreated(SurfaceHolder holder) { mThread.setRunning(true); mThread.start(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); } private void makeGraphic() { Bitmap cellImageSource = BitmapFactory.decodeResource(getResources(), R.drawable.cell); imageCell = Bitmap.createScaledBitmap(cellImageSource, cellSize, cellSize, false); imageRobot = BitmapFactory.decodeResource(getResources(), R.drawable.robot); imageHero = BitmapFactory.decodeResource(getResources(), R.drawable.hero); } private void constructRobots() { Robot robot; Random rand = new Random(); for (int r = 0; r < robotCount; r++) { int x = rand.nextInt(sizeX); int y = rand.nextInt(sizeY); robot = new Robot(this, x, y, imageRobot); robots.add(robot); } return; } private void constructCells() { Cell cell; for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { cell = new Cell(this, x, y, imageCell); cells.add(cell); } } return; } protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); Cell cell; for (int c = 0; c < cells.size(); c++) { cell = cells.get(c); cell.onDraw(canvas); } Robot robot; for (int r = 0; r < robots.size(); r++) { robot = robots.get(r); robot.onDraw(canvas); } hero.onDraw(canvas); } public boolean onTouchEvent(MotionEvent e) { int shotX = (int) e.getX(); int shotY = (int) e.getY(); if (e.getAction() == MotionEvent.ACTION_MOVE){ //TODO move board showToast("move Board"); } else if (e.getAction() == MotionEvent.ACTION_UP) { showToast("touchPoint: " + shotX + ", "+shotY); hero.moveByDirection(shotX, shotY); this.scrollTo(shotX, shotY); } return true; } public void showToast(String mes) { Toast toast = Toast.makeText(getContext(), mes, Toast.LENGTH_LONG); toast.show(); } public class GameThread extends Thread { private BoardView view; public GameThread(BoardView view) { this.view = view; } public void setRunning(boolean run) { running = run; } public void run() { while (running) { Canvas canvas = null; try { canvas = view.getHolder().lockCanvas(); synchronized (view.getHolder()) { onDraw(canvas); } canvas.scale(300, 300); } catch (Exception e) { } finally { if (canvas != null) { view.getHolder().unlockCanvasAndPost(canvas); } } } } } } Some magic digits here are temporary. Now I just want to move BoardView;
The issue was to add x and y fields to SurfaceView, change them at onTouchEvent and draw all the elements in canvas with x- and y-offset. It's strange that I didn't recieved any answers...