Home > Enterprise >  StartActivity in a Thread
StartActivity in a Thread

Time:02-17

Why does MainActivity not start after 1 sec?

class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    supportActionBar?.hide()
    setContentView(R.layout.activity_splash)
    Thread {
       Thread.sleep(1000)
       println("test")
       runOnUiThread {
           startActivity(Intent(this, MainActivity::class.java))
           this.finish()
       }
   }
}

Does anyone could help me please.

CodePudding user response:

Thread.run(). You have to run the Thread.

CodePudding user response:

add thread.start(); after your thread curly braces. or you can follow my code

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
                doprogress();
                nectactivity();
        }
    });

    thread.start();
}

private void nectactivity() {
    Intent intent = new Intent(SpalshScreenActivity.this,MainActivity.class);
    startActivity(intent);
    finish();

}

private void doprogress() {
        try {
            Thread.sleep(1000);
           
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
}

CodePudding user response:

You need to add a new task flag

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  • Related