Home » Android » android – Close an Activity after 10 seconds?

android – Close an Activity after 10 seconds?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I use it to call another activity

Main.java

 Intent intent = new Intent(this, Message_Note.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);

Message_Note.java :

public class Message_Note extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message);
    }



}

How can i CLOSE the Message_Note Activity after 10 seconds ?? i should use a thread ?

How to&Answers:

After 100 MS, the activity will finish using the following code.

public class Message_Note extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message);

        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {
            public void run() {
                finish();
            }
        }, 100);
    }
}

Answer:

You can use following approach.

Approach 1

int finishTime = 10; //10 secs
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        YourActivity.this.finish();
    }
}, finishTime * 1000);

Approach 2

int FinishTime = 10;
int countDownInterval = 1000; 
counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
    public void onFinish() {
        //finish your activity here
    }

    public void onTick(long millisUntilFinished) {
        //called every 1 sec coz countDownInterval = 1000 (1 sec)
    }
};
counterTimer.start();

Answer:

You can use AlarmManager. See :

http://developer.android.com/reference/android/app/AlarmManager.html

and

Alarm Manager Example

Answer:

Another way is just like this:

new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            Message_Note.this.finish();
        }
    }, 10000);