how to add layouts in android livewallpaper - java

i have created live wallpaper using canvas now i want to add the layout like(relative layout)
if its possible?
in live wallpaper we can able to use layout?
please guide me how to add layout here if its possible?
if possible means how can i called that layout in my canvas class?
in this canvas how can i overwrite the ondraw mathod?
i have searched hole internet i can't able to fine any information.
i'm new to android live wallpaper and jave plz guide me.
here is my code
public class AquariumWallpaperService extends WallpaperService {
private float mTouchX = -1;
private float mTouchY = -1;
int count = 1;
public AquaticAnimal animal;
public static final String SHARED_PREFS_NAME = "livewallpapertemplatesettings";
#Override
public Engine onCreateEngine() {
return new AquariumWallpaperEngine();
}
class AquariumWallpaperEngine extends Engine {
private Aquarium aquarium;
public AquariumWallpaperEngine() {
this.aquarium = new Aquarium();
this.aquarium.initialize(getBaseContext(), getSurfaceHolder());
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// By default we don't get touch events, so enable them.
setTouchEventsEnabled(true);
}
#Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
this.aquarium.render();
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
this.aquarium.start();
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.aquarium.stop();
}
}
this is my canvas class
public class Aquarium {
private AquariumThread aquariumThread;
private SurfaceHolder surfaceHolder;
private ArrayList<Renderable> fishes;
private Bitmap backgroundImage, backgroundImage1;
private Bitmap boble;
public Boolean bgchange = false;
private Context context;
public int count = 1, x = 100, y = 500, x1 = 400, y1 = 500, x2 = 10,
y2 = 250;
public AquariumWallpaperEngine aqua;
public void render() {
Canvas canvas = null;
try {
count++;
if (count > 5) {
if (count % 8 == 0) {
x2++;
y--;
y1--;
}
}
if (y == -20) {
y = 600;
y1 = 600;
}
if (x2 == 700) {
x2 = -20;
}
if (count > 3000) {
bgchange = true;
}
if (count > 6000) {
bgchange = false;
count = 0;
}
//System.out.println("count" + count);
canvas = this.surfaceHolder.lockCanvas(null);
synchronized (this.surfaceHolder) {
this.onDraw(canvas);
}
} finally {
if (canvas != null) {
this.surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
protected void onDraw(Canvas canvas) {
this.renderBackGround(canvas);
for (Renderable renderable : this.fishes) {
renderable.render(canvas);
}
};
public void start() {
this.aquariumThread.switchOn();
}
public void stop() {
boolean retry = true;
this.aquariumThread.switchOff();
while (retry) {
try {
this.aquariumThread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
public int getLeft() {
return 0;
}
public int getRight() {
return this.backgroundImage.getWidth();
}
public int getRightbg() {
return this.backgroundImage1.getWidth();
}
public void initialize(Context context, SurfaceHolder surfaceHolder) {
this.aquariumThread = new AquariumThread(this);
this.surfaceHolder = surfaceHolder;
this.fishes = new ArrayList<Renderable>();
this.context = context;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
this.backgroundImage = BitmapFactory.decodeResource(
context.getResources(), com.thinkpal.live.R.drawable.aquarium,
options);
this.backgroundImage1 = BitmapFactory.decodeResource(
context.getResources(), com.thinkpal.live.R.drawable.waquarium,
options);
this.boble = BitmapFactory.decodeResource(context.getResources(),
com.thinkpal.live.R.drawable.bubble, options);
this.addFishes();
}
private void addFishes() {
Point startPoint = new Point(100, 100);
this.fishes.add(new ClownFish(this.context, this, startPoint, 90));
Point startPoint1 = new Point(100, 300);
this.fishes.add(new ClownFish(this.context, this, startPoint1, 50));
Point startPoint2 = new Point(200, 200);
this.fishes.add(new ClownFish(this.context, this, startPoint2, 15));
}
private void renderBackGround(Canvas canvas) {
Paint paint = new Paint();
canvas.drawBitmap(this.backgroundImage, 0, 0, null);
if (bgchange) {
canvas.drawBitmap(this.backgroundImage1, 0, 0, null);
}
canvas.drawBitmap(this.boble, x, y, null);
canvas.drawBitmap(this.boble, x1, y1, null);
canvas.drawBitmap(this.boble, x2, y2, null);
canvas.drawText("Think palm", x + 10, y + 45, paint);
canvas.drawText("Cochin", x1 + 20, y1 + 45, paint);
canvas.drawText("Welcome to", x2 + 10, y2 + 45, paint);
}
}

YOu could always call getTheme() in WallpaperService and then apply layouts to that, not sure what use it will be to you though. It looks like you've already got everything working, wouldn't really bother with layouts if I were you...

Related

Can't implement toggle button function outside of one screen

Hi I've implemented a toggle button for sound on my SettingsMenu, it works within this screen however when I go back to my main menu the functionality is lost and it resets back to its initial state. Any ideas how I can make it so that once it is clicked, it keeps this selection throughout every screen. I will show you the toggle button class and the settings class in which it is implemented. Thanks.
package uk.ac.qub.eeecs.game.cardDemo;
public class ToggleButtonSound extends GameObject {
protected enum ButtonState {
ON, OFF
}
private ButtonState mButtonState = ButtonState.OFF;
private SoundManager sm;
protected Bitmap mOffBitmap;
protected Bitmap mOnBitmap;
protected Bitmap mOnHoverBitmap;
protected Bitmap mOffHoverBitmap;
private Game mGame;
public boolean mMusicMuted = false;
public boolean mSoundMuted = false;
private MusicManager mMusicManager;
public ToggleButtonSound(float x, float y, float width, float height,
String offBitmap,
String onBitmap,
// String OffHoverBitmap,
//String OnHoverBitmap,
GameScreen gameScreen,
Game game) {
super(x, y, width, height,
gameScreen.getGame().getAssetManager().getBitmap(offBitmap), gameScreen);
mGame = game;
AssetStore assetStore = gameScreen.getGame().getAssetManager();
mOffBitmap = assetStore.getBitmap(offBitmap);
// mOffHoverBitmap = assetStore.getBitmap(offBitmap);
mOnBitmap = assetStore.getBitmap(onBitmap);
//mOnHoverBitmap = assetStore.getBitmap(onBitmap);
sm = new SoundManager(mGame);
mMusicManager = new MusicManager(mGame);
}
private boolean mPushTriggered;
private boolean mIsPushed;
/**
* Update the button
*
* #param elapsedTime Elapsed time information
*/
public void update(ElapsedTime elapsedTime) {
// Consider any touch events occurring in this update
Input input = mGame.getInput();
BoundingBox bound = getBound();
// Check for a press release on this button
for (TouchEvent touchEvent : input.getTouchEvents()) {
if (touchEvent.type == TouchEvent.TOUCH_UP
&& bound.contains(touchEvent.x, touchEvent.y)) {
// A touch up has occured in this control
if (mButtonState == ButtonState.OFF) {
setToggled(true);
} else {
setToggled(false);
}
return;
}
}
for (int idx = 0; idx < TouchHandler.MAX_TOUCHPOINTS; idx++) {
if (input.existsTouch(idx)) {
if (bound.contains(input.getTouchX(idx), input.getTouchY(idx))) {
if (!mIsPushed) {
mPushTriggered = true;
if (mOnHoverBitmap != null && mOffHoverBitmap != null)
mBitmap = mButtonState == ButtonState.ON ? mOnHoverBitmap : mOffHoverBitmap;
mIsPushed = true;
}
return;
}
}
}
if (mIsPushed) {
mBitmap = mButtonState == ButtonState.ON ? mOnBitmap : mOffBitmap;
mIsPushed = false;
mPushTriggered = false;
}
}
public boolean isToggledOn() {
return mButtonState == ButtonState.ON;
}
public void setToggled(boolean on) {
if (on) {
mButtonState = ButtonState.ON;
mBitmap = mOnBitmap;
} else {
mButtonState = ButtonState.OFF;
mBitmap = mOffBitmap;
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D,
LayerViewport layerViewport, ScreenViewport screenViewport) {
// Assumed to be in screen space so just draw the whole thing
drawScreenRect.set((int) (position.x - mBound.halfWidth),
(int) (position.y - mBound.halfWidth),
(int) (position.x + mBound.halfWidth),
(int) (position.y + mBound.halfHeight));
graphics2D.drawBitmap(mBitmap, null, drawScreenRect, null);
}
}
Settings menu
public class SettingsMenu extends GameScreen {
private ToggleButtonSound mToggleButtonSound;
public SettingsMenu(Game game) {
super("Settings Menu", game);
mSoundManager = new SoundManager(game);
mMenuScreen = new MenuScreen(game);
music = new MusicManager(game);
AssetStore assetManager = mGame.getAssetManager();
assetManager.loadAndAddBitmap("offswitch", "img/offswitch.png");
assetManager.loadAndAddBitmap("onswitch", "img/onswitch.png");
assetManager.loadAndAddBitmap("SoundOn", "img/Soundon.png");
assetManager.loadAndAddBitmap("SoundOff", "img/Soundoff.png");
assetManager.loadAndAddBitmap("SettingsBackground", "img/settingsbackground.png");
//Load in sound
assetManager.loadAndAddSound("mouseClick", "Sounds/clicksound.wav");
assetManager.loadAndAddMusic("BackgroundMusic", "Sounds/MenuScreenBackgroundMusic.mp3");
//initialise sound
int spacingX = mGame.getScreenWidth() / 3;
int spacingY = mGame.getScreenHeight() / 9;
mPlayButtonBound = new Rect(spacingX, 3 * spacingY, 2 * spacingX, 4 * spacingY);
mInventoryButtonBound = new Rect(spacingX, 5 * spacingY, 2 * spacingX, 6 * spacingY);
soundButtonBound = new Rect(game.getScreenWidth() / 100, game.getScreenWidth() / 100, game.getScreenWidth() / 10, game.getScreenWidth() / 10);
mSettingsBackground = new Rect(1, 1, game.getScreenWidth(), game.getScreenHeight());
mLayerViewport = new LayerViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
mScreenViewport = new ScreenViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
int toggleHeight = mGame.getScreenHeight()/3;
mToggleButtonMusic = new ToggleButtonMusic(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch","onswitch","offswitch", this, mGame);
mToggleButtonSound = new ToggleButtonSound(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch", this, mGame);
mToggleButtonMusic.setPosition(game.getScreenWidth()/2,game.getScreenHeight()/3);
mToggleButtonSound.setPosition(game.getScreenWidth()/2, toggleHeight*2);
//toggleB.getBitmap();
//toggleB.getBound();
}
private boolean mIsPushed;
#Override
public void update(ElapsedTime elapsedTime) {
music.isPlaying1();
//mToggleButtonSound.setToggled(soundMuted);
mToggleButtonMusic.update(elapsedTime);
mToggleButtonSound.update(elapsedTime);
Input input = mGame.getInput();
List<TouchEvent> touchEvents = input.getTouchEvents();
if (touchEvents.size() > 0) {
TouchEvent touchEvent = touchEvents.get(0);
if (touchEvent.type == TouchEvent.TOUCH_UP) {
if ((soundButtonBound.contains((int) touchEvent.x, (int) touchEvent.y))) {
mGame.getScreenManager().removeScreen("Settings Menu");
mMenuScreen = new MenuScreen(mGame);
mGame.getScreenManager().addScreen(mMenuScreen);
}
}
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SettingsBackground"), null, mSettingsBackground, null);
mToggleButtonMusic.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
mToggleButtonSound.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SoundOn"), null, soundButtonBound, null);
}
#Override
public boolean onBackPressed() {
return true;
}
}

Collision Detection is Not Working

Basically I have been making a simple game in which I now want to create collision detection between the Player and the Enemy. I have made both a class of the player and the enemy and then also a separate GameView class. My issue is that there is simply no collision happening and I just don't understand why, I have changed the code various times but I still can't seem to crack it. I will leave my code below and if anyone sees where I have gone wrong it would be great help. Thank you.
GameView Class:
public class GameView extends SurfaceView implements Runnable {
Canvas canvas;
SurfaceHolder surfaceHolder;
Thread thread = null;
volatile boolean playing;
Paint paint;
Context context;
Player player;
int screenX, screenY, numberOfEnemies = 4, distanceBetweenEnemies;
int enemyX [] = new int[numberOfEnemies];
int enemyY [] = new int[numberOfEnemies];
private boolean paused = true;
Enemy enemy;
Enemy [] enemies;
Random random;
Rect [] enemyRectangle;
public GameView (Context context, int x, int y) {
super(context);
this.context = context;
surfaceHolder = getHolder();
paint = new Paint();
thread = new Thread();
screenX = x;
screenY = y;
player = new Player (context, screenX, screenY);
enemies = new Enemy[numberOfEnemies];
enemyRectangle = new Rect[numberOfEnemies];
enemy = new Enemy (context, screenX);
distanceBetweenEnemies = screenX * 3 / 4;
for (int i = 0; i < numberOfEnemies; i ++) {
enemies[i] = new Enemy(context, screenX);
enemyX[i] = screenX / 2 - enemy.getEnemyBitmap().getWidth() / 2 + i * distanceBetweenEnemies;
random = new Random();
enemyY[i] = random.nextInt(screenY - enemy.getEnemyBitmap().getHeight() / 2);
}
}
#Override
public void run() {
while (playing) {
draw();
if(!paused){
update();
}
}
}
private void draw () {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.argb(255, 26, 128, 182));
canvas.drawBitmap(player.getPlayerBitmap(), player.getX(), player.getY(), null);
for (int i = 0; i < numberOfEnemies; i ++) {
canvas.drawBitmap(enemies[i].getEnemyBitmap(), enemyX[i], enemyY[i], null);
enemyRectangle [i] = new Rect(enemyX[i], enemyY[i], enemy.getEnemyBitmap().getWidth(),
enemy.getEnemyBitmap().getHeight());
enemyX[i] += enemy.getEnemySpeed();
}
update ();
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void update () {
player.updatePlayerPosition();
player.noLeaveScreen();
for (int i = 0; i < numberOfEnemies; i ++) {
if (enemyX[i] < 0 - enemy.getEnemyBitmap().getWidth()) {
enemyY[i] = random.nextInt(screenY);
enemyRectangle [i] = new Rect(enemyX[i], enemyY[i], enemy.getEnemyBitmap().getWidth(),
enemy.getEnemyBitmap().getHeight());
enemyX[i] += numberOfEnemies * distanceBetweenEnemies;
} else {
enemyX[i] += enemy.getEnemySpeed();
}
if (Rect.intersects(player.getPlayerRectangle(), enemyRectangle[i])) {
Log.e("COLLISION:", "Detected");
enemyX[i] = - 200;
}
}
}
public void pause () {
playing = false;
try {
thread.join();
} catch (InterruptedException e) {
Log.e("Error:", "joining thread");
}
}
public void resume () {
playing = true;
thread = new Thread(this);
thread.start();
}
#Override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
player.playerJump();
break;
}
return true;
}
}
Player Class:
public class Player {
Bitmap playerBitmap;
Rect playerRectangle;
int x, y, playerJumpSpeed, gravity, screenY;
boolean playerIsMoving;
public Player (Context context, int screenX, int screenY) {
this.screenY = screenY;
gravity = 2;
playerBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
x = screenX/2 - playerBitmap.getWidth()/2;
y = screenY/2 - playerBitmap.getHeight()/2;
playerRectangle = new Rect(x, y, playerBitmap.getWidth(), playerBitmap.getHeight());
playerJumpSpeed = - 1000;
playerIsMoving = true;
}
public void updatePlayerPosition () {
while (playerIsMoving) {
y += gravity;
break;
}
}
public void playerJump () {
while (playerIsMoving) {
y += playerJumpSpeed;
break;
}
}
public void noLeaveScreen () {
if (y < 0) {
playerJumpSpeed = 0;
} else {
playerJumpSpeed = - 40;
}
if (getY() > (screenY - playerBitmap.getHeight())) {
gravity = 0;
} else {
gravity = 2;
}
}
public int getX () {
return x;
}
public int getY () {
return y;
}
public Bitmap getPlayerBitmap () {
return playerBitmap;
}
public Rect getPlayerRectangle () {
return playerRectangle;
}
}
Enemy Class:
public class Enemy {
Bitmap enemyBitmap;
int enemySpeed, screenX;
boolean isEnemyMoving;
Random random;
public Enemy (Context context, int screenX) {
this.screenX = screenX;
enemyBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
random = new Random();
isEnemyMoving = true;
enemySpeed = - 3;
}
public int getEnemySpeed () {
return enemySpeed;
}
public Bitmap getEnemyBitmap () {
return enemyBitmap;
}
}
There are the classes, any help appreciated!

Cannot scale background image (android studio)

public class GameView extends SurfaceView {
private Bitmap bmp;
private SurfaceHolder holder;
private GameLoopThread gameLoopThread;
private int x = 0;
private int y = 0;
private int xSpeed = 1;
public static int WIDTH = 800;
public static int HEIGHT = 450;
private Background bg;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#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) {
bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.tuo));
bg.setVector(-5);
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic);
// tutaj dorysować tło
}
#Override
protected void onDraw(Canvas canvas) {
if (x == getWidth() - bmp.getWidth()) {
xSpeed = -4;
}
if (x == 0) {
xSpeed = 4;
}
x = x + xSpeed;
final float scaleFactorX = getWidth()/WIDTH;
final float scaleFactorY = getHeight()/HEIGHT;
if(canvas!=null) {
final int savedState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
bg.draw(canvas);
canvas.restoreToCount(savedState);
}
canvas.drawBitmap(bmp, x , 10, null);
}
public void update()
{
bg.update();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
x=x+10;
return super.onTouchEvent(event);
}
}
I can't scale the image - it should make a scale by dividing getWidth/WIDTH (and height too) - WIDTH and HEIGHT are the image dimensions.
It just prints a left, upper corner of an image, like there is totally no scaling ;(
If someone have any idea, I would be thankful :)
u need to calc:
/*
WIDTH/getWidth() = 4; // if ur image width = 200px
scaleFactorX = 4*getwidth();
scaleFactorY = 4*getHeight();
*/
final float scaleFactorX = WIDTH/getWidth();
final float scaleFactorY = HEIGHT/getHeight();
canvas.scale(scaleFactorX*getWidth(), scaleFactorY*getHeight());
i hope they are proportionaly...
1600*900 or something like this... 400*225

How to check if the screen has not been touched

I have a game that displays circles randomly on the screen. The circles can be green or red at random. If you touch a red circle something happens; if you touch a green circle something happens; but what if you wanted to check if the green circle was displayed and a user did not click it? Here is my code:
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
public static int highestScore = 0;
boolean isTouched;
Thread newThread = new Thread();
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(lastColor == greenColor){
isTouched = false;
}
if(addPoints < 10){
handler.postDelayed(this, 850);
}
if(addPoints > 9 && addPoints < 30){
handler.postDelayed(this,700);
}
if(addPoints > 29){
handler.postDelayed(this, 600);
}
if(addPoints > 50){
handler.postDelayed(this, 450);
}
if(addPoints > 100){
handler.postDelayed(this, 400);
}
postInvalidate();
}
};
public void what(){
try {
newThread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("Beta v2", 10, 60, newPaint);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
what();
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(lastColor == redColor){
//saveScore();
howManyPoints = addPoints;
if(howManyPoints > highestScore){
highestScore = howManyPoints;
}
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
}
}else {
}
}
return false;
}
public void saveScore() {
a.add("" + addPoints);
//if(Integer.parseInt(savedScores[1]) < addPoints){
//savedScores[2] = savedScores[1];
//int x = Integer.parseInt(savedScores[1]);
//x = addPoints;
//}
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
Just add a boolean hasBeenClicked that is false and becomes true when the user touches it

How to turn a gif into a live wallpaper for use in Android app

I don't need a fancy wallpaper which moves with your phone, I would just like to use a gif as a moving "live" wallpaper. Is this possible, and if so, could anyone explain to me how it is done, or point me to a resource which demonstrates how? I have been unable to find one as of yet.
See GIFLiveWallpaper demo look out at github repo
public class GifLiveWallPaper extends WallpaperService {
static final String TAG = "LIVE_WALLPAPER";
static final Handler liveHandler = new Handler();
#Override
public Engine onCreateEngine() {
try {
return new WallPaperEngine();
} catch (IOException e) {
Log.w(TAG, "Error creating WallPaperEngine", e);
stopSelf();
return null;
}
}
class WallPaperEngine extends Engine {
private Movie liveMovie;
private int duration;
private Runnable runnable;
float mScaleX;
float mScaleY;
int mWhen;
long mStart;
public WallPaperEngine() throws IOException {
InputStream is = getResources().openRawResource(R.raw.sam);
if (is != null) {
try {
liveMovie = Movie.decodeStream(is);
duration = liveMovie.duration();
} finally {
is.close();
}
} else {
throw new IOException("Unable to open R.raw.hand");
}
mWhen = -1;
runnable = new Runnable() {
public void run() {
nyan();
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
liveHandler.removeCallbacks(runnable);
}
#Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
nyan();
} else {
liveHandler.removeCallbacks(runnable);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
mScaleX = width / (1f * liveMovie.width());
mScaleY = height / (1f * liveMovie.height());
nyan();
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
xPixelOffset, yPixelOffset);
nyan();
}
void nyan() {
tick();
SurfaceHolder surfaceHolder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
drawGif(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
liveHandler.removeCallbacks(runnable);
if (isVisible()) {
liveHandler.postDelayed(runnable, 1000L / 25L);
}
}
void tick() {
if (mWhen == -1L) {
mWhen = 0;
mStart = SystemClock.uptimeMillis();
} else {
long mDiff = SystemClock.uptimeMillis() - mStart;
mWhen = (int) (mDiff % duration);
}
}
void drawGif(Canvas canvas) {
canvas.save();
canvas.scale(mScaleX, mScaleY);
liveMovie.setTime(mWhen);
liveMovie.draw(canvas, 0, 0);
canvas.restore();
}
}
}

Categories

Resources