문제

I want my activity to show a screen for 3 seconds, then go back to previous screen. But when i use

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome_layout);
        TextView tvResult = (TextView)findViewById(R.id.textView1)
        Thread.sleep(3000);
            Intent i = new Intent(this,myActivity.class);
            startActivity(i);

But unfortunately, this does not work. This doesent show the activity waits 3 seconds and goes back. However, i want it to show its contents before going back. How can i do it ?

도움이 되었습니까?

해결책

You should remove this Thread.sleep(3000); which block the ui thread. You should never block the ui thred. You can use a Handler postDelayed with a delay and then startActivtiy.

Handler handler = new Handler();
handler.postDelayed(new Runnable(){
@Override
  public void run(){
   // do something
 }
 }, 3000);

To go back to previous Activity you can call finish().

Also if you need to go back to the previous activity for 3 seconds why do you need

Intent i = new Intent(this,myActivity.class);
startActivity(i);

Calling finish() will do the job

다른 팁

This is not the recommended way to do this. Using Thread.sleep you're blocking the main UI thread for 3000 milliseconds. This means that nothing in the activity will work until 3 seconds are passed.

Instead, you could do this: edited: now it works well.

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome_layout);
    TextView tvResult = (TextView)findViewById(R.id.textView1)
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                Thread.sleep(3000);
                Intent i = new Intent(getApplicationContext(), myActivity.class);
                startActivity(i);
            }
            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top