简体   繁体   中英

Game not start again when Home button pressed once's.

I am working on a game. When I press the home button on my device my game is closed. When I launch it again my game doesn't start until I've cleared the memory of my device. please solve my problem thanks in advance. Here's my mainActivity of the game:

public class Game extends Activity {

MediaPlayer backgroungMusic;
Toast toast;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //   setContentView(R.layout.activity_game);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);



    //turn title off
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // set full screen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(new GamePanel(this));

    backgroungMusic = MediaPlayer.create(Game.this, R.raw.music);
    backgroungMusic.setLooping(true);
    backgroungMusic.start();

}


@Override
protected void onPause()
{

    super.onPause();
    backgroungMusic.release();
    finish();
}



@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {


        //  GamePanel.thread.setStoped(true);
        GamePanel.thread.setRunning(false);
        // in the next line of code we also style the dialog through xml which i put in styles
        AlertDialog alertDialog = new AlertDialog.Builder(this,R.style.myBackgroundStyle).create();
        alertDialog.setTitle("Exit Alert");
        alertDialog.setMessage("Do you really want to exit the Game?");
        alertDialog.setButton("Quit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //Best way is firstly use finish() and after that use System.exit(0) to clear static variables. It will give you some free space.
                // A lot of applications leave working processes and variables what makes me angry. After 30 minutes of using memory is full and i have to run Task Manager - Lvl 2 clear memory
                finish();
                System.exit(0);
                return;

            }
        });


        alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        // dialog.cancel();
                        // GamePanel.thread.resume();
                        dialog.dismiss();
                        // When user press the "Cancle" button then game resume for 3 seconds then start again
                        // Here is the Code of the toasts and each toast appear with delay of one second.

                        toast = new Toast(Game.this);
                        TextView textView = new TextView(Game.this);
                        textView.setTextColor(Color.DKGRAY);
                        textView.setBackgroundColor(Color.TRANSPARENT);
                        textView.setTextSize(60);
                        textView.setText("READY!");
                        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

                        toast.setView(textView);
                        toast.show();

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // show toast 2.
                                toast = new Toast(Game.this);
                                TextView textView = new TextView(Game.this);
                                textView.setTextColor(Color.DKGRAY);
                                textView.setBackgroundColor(Color.TRANSPARENT);
                                textView.setTextSize(140);
                                textView.setText("3");
                                // textView.setText("done!");
                                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

                                toast.setView(textView);
                                toast.show();
                            }
                        }, 2500);


                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // show toast 2.
                                toast = new Toast(Game.this);
                                TextView textView = new TextView(Game.this);
                                textView.setTextColor(Color.DKGRAY);
                                textView.setBackgroundColor(Color.TRANSPARENT);
                                textView.setTextSize(140);
                                textView.setText("2");
                                // textView.setText("done!");
                                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

                                toast.setView(textView);
                                toast.show();
                            }
                        }, 5000);

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // show toast 3. Init game.
                                toast = new Toast(Game.this);
                                TextView textView = new TextView(Game.this);
                                textView.setTextColor(Color.DKGRAY);
                                textView.setBackgroundColor(Color.TRANSPARENT);
                                textView.setTextSize(140);
                                textView.setText("1");
                                // textView.setText("done!");
                                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

                                toast.setView(textView);
                                toast.show();

                            }
                        }, 7500);

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // show toast 3. Init game.
                                GamePanel.thread.setRunning(true);
                            }
                        }, 10000);


                        return;
                    }
                }

        );


        alertDialog.show();

        return true;
    }
    return super.onKeyDown(keyCode, event);

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_game, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}}

It is essential to FULLY understand the activity life cycle of an Android App.

Read this page carefully:

https://developer.android.com/reference/android/app/Activity.html

What is happening in your code is that you have only onCreate() and onPause().

You need to add code to properly restart your app after switching back to it.

The code must be added in onRestart(). Move your code from onPause() to onStop() instead.

So you will get cycle of onStop() -> onRestart() -> onStop() -> onRestart() and so on ...

When you click the home button onStop() will be called and when you go back to it onRestart() will be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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