简体   繁体   English

屏幕关闭时存储活动状态

[英]Storing the Activity's state when the screen turns off

I'm developing an android game, trying to store the character's coordinates. 我正在开发一个Android游戏,试图存储角色的坐标。 I'm using the onSaveInstanceState and onRestoreInstanceState methods. 我正在使用onSaveInstanceStateonRestoreInstanceState方法。 But when I tested the coordinates get's changed. 但是当我测试坐标时,得到的改变了。

So it loads the correct value but after that it saves a bad number then it loads this bad value. 因此,它加载正确的值,但之后保存一个错误的数字,然后加载该错误的值。

Class1 1类

package hu.cig.vob;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import cug.hu.vob.R;

public class Level extends Activity {
    private LevelView lv;
    private LinearLayout linearL;
    private Button left, right, jump, fire;
    private mListener l = new mListener();

    //Konstansok az activity allapotanak mentesehez
    private  String playerX = "PlayerX",playerY="PlayerY",playerH="PlayerH";

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.level_layout);

        final ImageView healthBar = (ImageView) findViewById(R.id.life_view);

        Drawable d = getResources().getDrawable(R.drawable.main_screen_bg);
        linearL = (LinearLayout) findViewById(R.id.linear_layout);
        linearL.setBackgroundDrawable(d);

        lv = new LevelView(getApplicationContext(), getIntent().getIntExtra(
                MainActivity.LEVEL_EXTRA, 0), getWindowManager());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT);
        lv.setLayoutParams(params);
        linearL.addView(lv, 0);

        left = (Button) findViewById(R.id.left);
        right = (Button) findViewById(R.id.right);
        jump = (Button) findViewById(R.id.jump);
        fire = (Button) findViewById(R.id.fire);

        left.setOnTouchListener(l);
        right.setOnTouchListener(l);
        jump.setOnTouchListener(l);
        fire.setOnTouchListener(l);

        lv.setOnClickListener(new OnClickListener() {
//      Game over screen esetén kilép
            @Override
            public void onClick(View v) {
                if (lv.getGameState()) {
                    finish();
                }
            }
        });
//      Életcsik frissitése az életnek megfelelően
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    if (lv.getRobot().getHealth() <= 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                healthBar.setImageResource(R.drawable.battery5);

                            }
                        });

                    } else if (lv.getRobot().getHealth() <= 25) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                healthBar.setImageResource(R.drawable.battery4);

                            }
                        });
                    } else if (lv.getRobot().getHealth() <= 50) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                healthBar.setImageResource(R.drawable.battery3);

                            }
                        });
                    } else if (lv.getRobot().getHealth() <= 75) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                healthBar.setImageResource(R.drawable.battery2);

                            }
                        });
                    }else if(lv.getRobot().getHealth() >= 75){
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                healthBar.setImageResource(R.drawable.battery);

                            }
                        });
                    }
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }.start();
    }

    @Override
    protected void onPause() {
        overridePendingTransition(0, 0);
        super.onPause();
    }



//  TODO:
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        lv.getRobot().setX(savedInstanceState.getInt(playerX));
        lv.getRobot().setY(savedInstanceState.getInt(playerY));
        Log.d("LoL","Loaded y:"+savedInstanceState.getInt(playerY));
        lv.getRobot().setHealth(savedInstanceState.getInt(playerH));
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putInt(playerX , lv.getRobot().getX());
        outState.putInt(playerY, lv.getRobot().getY());
        Log.d("LoL","Saved y:"+lv.getRobot().getY());
        outState.putInt(playerH, lv.getRobot().getHealth() );
        super.onSaveInstanceState(outState);
    }



//  iránygombok kezelése
    private class mListener implements OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                switch (v.getId()) {
                case R.id.left:
                    lv.getRobot().moveLeft();
                    break;
                case R.id.right:
                    lv.getRobot().moveRight();
                    break;
                case R.id.jump:
                    lv.getRobot().jump();
                    break;
                case R.id.fire:
                    lv.getRobot().shot();
                    break;
                }
                break;

            case MotionEvent.ACTION_UP:
                switch (v.getId()) {
                case R.id.left:
                    lv.getRobot().stopMovingLeft();
                    break;
                case R.id.right:
                    lv.getRobot().stopMovingRight();
                    break;
                case R.id.fire:
                    lv.getRobot()._shot();
                    break;
                }
                break;

            }
            return true;
        }

    }
}

class2 2级

package hu.cig.vob;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import cug.hu.vob.R;

public class Robot {
    private Bitmap icon, currIcon, iconShot;
    private int x, y, speedX = 0, speedY = 0, health = 100;
    private final int MOVESPEED = 3, JumpSpeed = 15;
    private boolean isMovingLeft = false, isMovingRight = false,
            isFalling = true, isJumping = false, canJump = true;
    private Rect bottom, horizontal;
    private Context context;
    private List<Bullet> bullets = Collections
            .synchronizedList(new ArrayList<Bullet>());


    public Robot(int in_x, int in_y, Bitmap i, float sc, Context c) {
        context = c;

        icon = i;
        currIcon = icon;
        iconShot = BitmapFactory.decodeResource(c.getResources(),
                R.drawable.shot_right);

        x = in_x * (icon.getWidth()/2);
        y = in_y * (icon.getHeight()/2);
        y = (int) (sc - y);

        // for colliding
        horizontal = new Rect((int) (x + icon.getWidth() * (31.5 / 100)),
                y + 5, (int) (x + icon.getWidth() - icon.getWidth()
                        * (31.5 / 100)), y + icon.getHeight() - 5);

        bottom = new Rect((int) (x + icon.getWidth() * (31.5 / 100) + 5), y
                + icon.getHeight() - 10, (int) (x + icon.getWidth()
                - icon.getWidth() * (31.5 / 100) - 5), y + icon.getHeight());
    }

    public void update(List<Block> blocks) {
        int oldX = x, oldY = y;
        if (!(x + speedX < 0 || x + speedX > LevelView.intScreenWidth)) {
            x += speedX;
        }

        updateRect();

        for (int i = 0; i < blocks.size(); i++) {
            if (horizontal.intersect(blocks.get(i).getRect())) {
                stopMovingRight();
                stopMovingLeft();
                x = oldX;
                updateRect();
            }
        }


        if (bullets.size() > 0) {
            Iterator<Bullet> it = bullets.iterator();
            while (it.hasNext()) {
                Bullet b = it.next();
                if (b.getCx() > LevelView.screenWidth) {
                    it.remove();
                } else {
                    b.update();
                }

                Iterator<Block> itt = blocks.iterator();
                while (itt.hasNext()) {
                    Block bb = itt.next();
                    if (bb.getRect().intersect(b.getRect())) {
                        it.remove();
                    }
                }
            }
        }


        // @graviti"

        if (isJumping) {
            y -= speedY;
            speedY--;
            if (speedY == 0) {
                isFalling = true;
                isJumping = false;
            }
            updateRect();
        }

        if (isFalling) {
            y += JumpSpeed - 5;
            canJump = false;
            updateRect();
        }

        for (Block b : blocks) {
            if (bottom.intersect(b.getRect())) {
                y = oldY;
                updateRect();
                canJump = true;
            }
        }
    }

    private void updateRect() {
        horizontal = new Rect((int) (x + icon.getWidth() * (31.5 / 100)),
                y + 10, (int) (x + icon.getWidth() - icon.getWidth()
                        * (31.5 / 100)), y + icon.getHeight() - 10);
        bottom = new Rect((int) (x + icon.getWidth() * (31.5 / 100) + 5), y
                + icon.getHeight() - 10, (int) (x + icon.getWidth()
                - icon.getWidth() * (31.5 / 100) - 5), y + icon.getHeight() - 2);
    }

    public void moveLeft() {
        speedX = -MOVESPEED;
        isMovingLeft = true;
    }

    public void moveRight() {
        speedX = MOVESPEED;
        isMovingRight = true;
    }

    public void stopMovingLeft() {
        isMovingLeft = false;
        stop();
    }

    public void stopMovingRight() {
        isMovingRight = false;
        stop();
    }

    public void stop() {
        if (isMovingRight == false && isMovingLeft == false) {
            speedX = 0;
        }

        if (isMovingRight == true && isMovingLeft == false) {
            moveRight();
        }

        if (isMovingRight == false && isMovingLeft == true) {
            moveLeft();
        }
    }

    public Bitmap getIcon() {
        return currIcon;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSpeed() {
        return speedX;
    }

    public boolean isMovingLeft() {
        return isMovingLeft;
    }

    public boolean isMovingRight() {
        return isMovingRight;
    }

    public Rect getBottomRect() {
        return bottom;
    }

    public Rect getHRect() {
        return horizontal;
    }

    public int getHealth() {
        return health;

    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public void shot() {
        currIcon = iconShot;
        Bullet b = new Bullet((float) (x + iconShot.getWidth()),
                (float) (y + ((26.31 * iconShot.getHeight()) / 100)),
                Helper.convertPx_Dpi(10, context), 2);
        bullets.add(b);
    }

    public void _shot() {
        currIcon = icon;
    }

    public List<Bullet> getBullets() {
        return bullets;
    }

    public void jump() {
        if (!isJumping && canJump) {
            isJumping = true;
            isFalling = false;
            speedY = JumpSpeed;
        }
    }



    public void increaseHealth(int x){
        health += x;
        if(health > 100){
            health = 100;
        }
    }

    public void degreeseHealth(int a) {
        health -= a;
    }
}

Your app can resume while obscured by the lock screen. 您的应用可以在被锁定屏幕遮住的情况下恢复。 If you want to tell the difference between "resume is hidden by a lock screen" and "resume is actually displayed" you can check your window focus. 如果您想告诉您“锁定屏幕隐藏了简历”和“实际显示了简历”之间的区别,则可以检查窗口焦点。

See Making Android Games that Play Nice for more details. 有关更多详细信息请参见制作可玩的Android游戏

A different way to get a similar "wait until actually displayed" is to wait for the first Activity.onUserInteraction after a resume before restarting your game. 获得类似的“等到实际显示之前”的另一种方法是,在恢复后等待第一个Activity.onUserInteraction ,然后重新启动游戏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM