屏幕关闭时存储活动的状态

时间:2014-07-12 17:35:13

标签: android android-activity android-lifecycle

我正在开发一款安卓游戏,试图存储角色的坐标。我使用onSaveInstanceStateonRestoreInstanceState方法。但是当我测试时,坐标会发生变化。

因此它加载了正确的值,但之后它会保存一个错误的数字,然后加载这个错误的值。

的Class1

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

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;
    }
}

1 个答案:

答案 0 :(得分:0)

您的应用可以在锁定屏幕遮挡时恢复。如果你想区分“恢复被锁定屏幕隐藏”和“恢复实际显示”之间的区别,你可以检查你的窗口焦点。

有关详细信息,请参阅Making Android Games that Play Nice

获得类似“等到实际显示”的另一种方法是在重新开始游戏之前等待恢复后的第一个Activity.onUserInteraction