5

I have a quiz app which has a timer for the whole gameactivity where in you should answer as much questions you can within the assigned minutes..

after the assigned minutes is over, it will take you to the results activity which shows your score. On back press,I created an alert dialog that asks if you want to go back to the main menu. If clicked on yes, the page should go back to the main menu and stop/kill the gameactivity.

However, when I click on "yes", it will go back to the main menu but while you are still anywhere in the application, the results would still show from the previous gameactivity i had. maybe i hadnt really finished the gameactivity, .. Here is the timer and back press snippet from my activity:

new CountDownTimer(seconds, 1000) {
    public void onTick(long millisUntilFinished) {
             timer.setText("Seconds left: " + millisUntilFinished / 1000);
    }   
    public void onFinish() {
             Intent intent = new Intent(GameActivityAddition.this, Score.class);
             intent.putExtra("totalscore", score);
             intent.putExtra("numberquestions", rowId);
             intent.putExtra("d", difficulty);
             db.close();
             startActivity(intent);
    }
}.start();

@Override
public void onBackPressed() {
    AlertDialog.Builder abuilder = new Builder(GameActivityAddition.this);
    abuilder.setMessage("Return to Main Menu?");
    abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            Intent main = new Intent(GameActivityAddition.this, Main.class);
            startActivity(main);
            finish();           
        }
    });
    abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();            
        }
    });
    AlertDialog alert = abuilder.create();
    alert.show();
}
Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
omi0301
  • 473
  • 2
  • 5
  • 15
  • 1
    Might be the data you have set in your result activity is not cleared when you finish off the activity,causing you to see older data when you again visit activity. – Hiral Vadodaria Sep 14 '12 at 07:06
  • You aren't stopping count down. – user996428 Sep 14 '12 at 07:15
  • I guess, just guess, the countdown timer works like a thread, which keeps running even when you call finish(). Try to add a boolean variable in the timer to control its running. – Huang Sep 14 '12 at 07:20

4 Answers4

2

There is no guarantee that finish() will close your current activity immediately(It is upto Android.)


To solve your problem try this,


Hold an reference to the timer (You will be using this to cancel the timer when User leaves the current Activity),

CountDownTimer resultTimer = new CountDownTimer(seconds, 1000) {
    public void onTick(long millisUntilFinished) {
             timer.setText("Seconds left: " + millisUntilFinished / 1000);
    }   
    public void onFinish() {
             Intent intent = new Intent(GameActivityAddition.this, Score.class);
             intent.putExtra("totalscore", score);
             intent.putExtra("numberquestions", rowId);
             intent.putExtra("d", difficulty);
             db.close();
             startActivity(intent);
    }
}.start();


and in onBackPressed() - cancel the Timer in setPositiveButton Callback,


@Override
public void onBackPressed() {
    AlertDialog.Builder abuilder = new Builder(GameActivityAddition.this);
    abuilder.setMessage("Return to Main Menu?");
    abuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            resultTimer.cancel(); //Stop the timer
            resultTimer = null;
            Intent main = new Intent(GameActivityAddition.this, Main.class);
            startActivity(main);
            finish();           
        }
    });
    abuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();            
        }
    });
    AlertDialog alert = abuilder.create();
    alert.show();
}
AjOnFire
  • 2,868
  • 3
  • 25
  • 39
  • 1
    _"There is no guarantee that finish() will close your current activity immediately(It is upto Android.)"_ -- This is wrong; when `finish()` is called, the activity is ended right away. What is _not_ ended is the process in which the activity lived. So any static data that was set during the activity will remain set. – Ted Hopp Sep 14 '12 at 07:21
  • My bad, I should have provided additional info. There is no gurantee that onDestroy of the activity will be called immediately (even if the Activity is completely removed from the screen) and memory retained not only corresponds to static data. – AjOnFire Sep 14 '12 at 07:25
  • @66CLSjY - THank you for your detailed answer. definitely solved it! :) – omi0301 Sep 14 '12 at 07:28
  • @66CLSjY please help me in http://stackoverflow.com/questions/13928591/a-strange-behavior-of-android-activities-fragments-and-intent – Amit Dec 21 '12 at 06:15
  • @TedHopp can you give a more elaborate answer about how to kill that process? – Relm Oct 15 '16 at 05:57
  • @Relm - See [this thread](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon) for doing this programmatically from within the app. You can also kill the process via adb (or the Android Monitor tool window in Android Studio, accessed from the View menu). You can also force stop the app from the Settings app on the device or X out the app from the app stack that pops up when you hit the recent apps button (or long press on the Home button, depending on the device version). – Ted Hopp Oct 16 '16 at 00:54
1

The property of CountDownTimer is , even you finished the activity it continues to countDown. If you want to stop this, put countTimerVar.cancel() when you finish() and in pressBackButton.

user996428
  • 96
  • 1
  • 7
  • You are right but it's even better to do it in the onPause.. method so timer will also stop when user uses home or switches app. At least if there is (like here) anything done with the ui. – FrankKrumnow Jan 22 '20 at 13:42
0

Finishing a parent activity from child activity can be implement by starting the child activity using the startActivityForResult and implement the onActivityResult to process the result return by the child activity. Example : From ParentActivity, start ChildActivity for a result using startActivityForResult(). Then, set a result that will inform ParentActivity to finish as well. Call finish() in ChildActivity . When ParentActivity receives that result from ChildActivity , ParentActivity calls finish() on itself as well. And there you can start another activity.

For code please refer: http://www.androidcompetencycenter.com/2009/03/tutorial-how-to-start-a-new-activity/

harshit
  • 3,788
  • 3
  • 31
  • 54
  • I have done exactly same in my app but the problem is when press back button on child Activity, the activity is paused and the onResume()s of Parent Activity and its fragments are called perfectly. However 1. Activity takes too much time in finishing and that looks like phone is hanged. 2. If next time I show any dialog it won't work, because the Child Activity is still their but not visible.... Now if I rotate the screen or go to some other fragment onStop and onDestroy of the child Activity is called and after that everything seems normal. – Amit Dec 21 '12 at 06:21
0

Another way might be to add a check for MyActivity.this.isFinishing() inside the timer:

public void onTick(long millisUntilFinished) {
    try{
         if(!MyActivity.this.isFinishing() )
            timer.setText("Seconds left: " + millisUntilFinished / 1000);
         //else: dont do anything
    }catch(Exception e){e.printStackTrace();}
} 

And the same for the onFinish().. then the timer should not do anything even when it doesn't get stopped by the activity. I also think that the timer will hold the activity alive for some time so it will maybe only go to onPause and not progress to onDestroy until the timer ends. I had a case with a thread where I interrupted the thread not in on pause but in onStop and it didn't reach that. So most things should be stopped/interrupted onPause at least if it does anything with UI like set a text.

FrankKrumnow
  • 501
  • 5
  • 13