当手机被锁定和解锁时,应用程序始终会调用onCreate()

时间:2013-07-28 08:05:11

标签: java android

有没有办法保存应用程序的状态,因为每次Android手机被锁定时应用程序都会调用onCreate()。当我解锁它时,应用程序调用onCreate()方法并重新开始.BTW我的应用程序就像文本扭曲。当我解锁屏幕时,会显示一个新单词,而不是当前单词。分数也会被重置以及时间..我该如何处理?请帮忙..它仍然没有答案..

这是我活动的全部代码..

public class friend extends Activity {

    //score
     ScoreHandler scHandler;
     Score sc;
     int totalScore;

     //words
    //DatabaseHelper dbHelp;
    DBHelper dbHelp;
    public String randomWord;

    //speech
    protected static final int RESULT_SPEECH = 1;
    private ImageButton btnSpeak;
    private TextView txtText;

    //shake
    private SensorManager mSensorManager;
    private ShakeEventListener mSensorListener;


    //timer
     private CountDownTimer countDownTimer;
        private boolean timerHasStarted = false;
        private TextView timeText;
        private final long startTime = 180 * 1000;
        private final long interval = 1 * 1000;
        private long timeLeft;

        private int gameScore;
        private TextView shuffleView;

        TextView scoreView;


    //Animation
        Animation myFadeInAnimation;
        Animation myFadeOutAnimation;
        Animation leftToRight;


    //sliding
            Button mCloseButton;
            Button mOpenButton;
            MultiDirectionSlidingDrawer mDrawer;

            Context context;

            static final String STATE_SCORE = "currentScore";
            static final String STATE_WORD = "currentWord";

            static final String STATE_TIME = "currentTime";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Check whether we're recreating a previously destroyed instance
        if (savedInstanceState != null) {
            // Restore value of members from saved state
             gameScore = savedInstanceState.getInt(STATE_SCORE);
            timeLeft = savedInstanceState.getLong(STATE_TIME);
            randomWord = savedInstanceState.getString(STATE_WORD);
        } else {
            // Probably initialize members with default values for a new instance
        }

        setContentView(R.layout.friend);

        leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);

        ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
        next.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
            Intent intent = new Intent();
            intent.setClass(friend.this, friend1.class);
            startActivity(intent);

            }
        });



        ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);

        giveUp.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setClass(friend.this, GameOverActivity.class);
                startActivity(intent);


            }
        });


      //score



    //timer

        timeText = (TextView) this.findViewById(R.id.timer);

        countDownTimer = new MyCountDownTimer(startTime, interval);
        timeText.setText(timeText.getText() + String.valueOf(startTime/1000));


            countDownTimer.start();
            timerHasStarted = true;

        this.removeAll();


         dbHelp = new DBHelper(this);


         randomWord = dbHelp.random();

         System.out.println(randomWord);

         String wordCaps = randomWord.toUpperCase();

         final String finalWord = shuffle(wordCaps);

        shuffleView = (TextView) findViewById(R.id.jumble);


         Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf"); 
         shuffleView.setTypeface(type);

        shuffleView.setText(finalWord);




        //shake
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorListener = new ShakeEventListener();   

        mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {

            public void onShake() {



            //String str = (String) stringList.remove(selectedWord);




            String wordOutput = shuffle(finalWord);

             TextView tv = (TextView) findViewById(R.id.jumble);

             tv.setText(wordOutput);

            }

        });





        //speech
        txtText = (TextView) findViewById(R.id.txtText);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });


    }



            public class MyCountDownTimer extends CountDownTimer {
            public MyCountDownTimer(long startTime, long interval) {
                super(startTime, interval);
            }



            @Override
            public void onFinish() {
                timeText.setText("0:00");
                playSound(R.raw.clock_whistle);

                ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);


                timeIsUp.startAnimation(leftToRight);



            }

            @Override
            public void onTick(long millisUntilFinished) {

                long minutes = (millisUntilFinished / (1000*60)) % 60;
                long seconds = (millisUntilFinished / 1000) % 60 ;
                timeLeft = millisUntilFinished/1000;

                timeText.setText("" + minutes + ":" + seconds );

                if (timeLeft <= 10) {
                    playSound(R.raw.clock_beep);
                }

            }
            }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {

                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                txtText.setText(text.get(0));
                System.out.println(""+text.get(0));
                String spoken = text.get(0);




                if(dbHelp.exists(spoken)){

                     if(dbHelp.isLongest(spoken)){

                       Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
                     }

                    gameScore = text.get(0).length()*10;
                    scoreView = (TextView) findViewById(R.id.scoreView);

                    scoreView.setText(""+gameScore);

                    scHandler = new ScoreHandler(this);
                    scHandler.addScore(new Score(1,gameScore));

                    int cumulativeScore = scHandler.accumulateScores();

                    scoreView.setText(""+cumulativeScore);

                    playSound(R.raw.correct);

                    WordGuessedHandler guessedWord = new WordGuessedHandler(this);

                    guessedWord.addGuessedWord(new Words(1,spoken));




                    ImageView img = (ImageView) findViewById(R.id.awesome);
                    myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
                    myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);


                    img.startAnimation(myFadeInAnimation);
                    img.startAnimation(myFadeOutAnimation);


               }else{


                     playSound(R.raw.poweng);

                     ImageView image = (ImageView) findViewById(R.id.wrong);
                     myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
                     myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);

                     image.startAnimation(myFadeInAnimation);
                     image.startAnimation(myFadeOutAnimation);


                }

    }

    }
   }

}

    public String shuffle(String input){
        List<Character> characters = new ArrayList<Character>();
        for(char c:input.toCharArray()){
            characters.add(c);
        }
        StringBuilder output = new StringBuilder(input.length());
        while(characters.size()!=0){
            int randPicker = (int)(Math.random()*characters.size());
            output.append(characters.remove(randPicker));

        }
        System.out.println(output.toString());

        return output.toString();

    } 


    @Override
    public void onBackPressed()
    {
        Intent inMain=new Intent(friend.this, MainActivity.class);
        inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(inMain);
        countDownTimer.cancel();
    }

    @Override
    protected void onResume() {
      super.onResume();
      mSensorManager.registerListener(mSensorListener,
          mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
          SensorManager.SENSOR_DELAY_UI);

    }

    @Override
    protected void onPause() {
      mSensorManager.unregisterListener(mSensorListener);
      super.onStop();

    }

    public void onSaveInstanceState(Bundle savedInstanceState) {
         // Save the user's current game state
        savedInstanceState.putInt(STATE_SCORE,gameScore);
        savedInstanceState.putLong(STATE_TIME,timeLeft);
        savedInstanceState.putString(STATE_TIME,randomWord);

        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);

        // Restore state members from saved instance
        gameScore = savedInstanceState.getInt(STATE_SCORE);
        timeLeft = savedInstanceState.getLong(STATE_TIME);
        randomWord = savedInstanceState.getString(STATE_WORD);
    }


    //sliding menu onChange
    @Override
    public void onContentChanged()
    {
        super.onContentChanged();

        mOpenButton = (Button) findViewById( R.id.button_open );
        mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);

    /*  GridView gridView;
        ArrayList ArrayofName = new ArrayList(); 
    WordHandler db = new WordHandler(this);*/

        TextView txt = (TextView) findViewById(R.id.text);



        txt.setText("Hello There!");


        GridView gridview = (GridView) findViewById(R.id.gridView1);

        WordGuessedHandler guessed = new WordGuessedHandler(this);

        List <WordGuessed> guessedList = guessed.getAllWordGuessed();

        List<String> wordsList = new ArrayList<String>();

        for(WordGuessed wg:guessedList){

            wordsList.add(wg.getWord());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, wordsList);

        gridview.setAdapter(adapter);


    }

    public void playSound(int sound) {

        MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);

        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
        mp.setLooping(false);
        mp.setVolume(1,1);
        mp.start();

    }


public void removeAll()
{

    ScoreHandler scHandler = new ScoreHandler(this);
    // db.delete(String tableName, String whereClause, String[] whereArgs);
    // If whereClause is null, it will delete all rows.
    SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
    db.delete("scores_table", null, null);
    db.close();

}

 }

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

请使用主Activity中的onPause()onResume()方法来解决此问题。如果两个方法都没有定义,那么您的应用将转到生命周期中的下一个方法,即onCreate()和其他方法。阅读更多here

也可以使用onSaveInstance(Bundle b)onRestoreInstance(Bundle b)

保存当前实例

PS:之前有人问过,并写了一个小例子来使用onSaveInstanceonRestoreInstance(如果你想使用它)here