简体   繁体   中英

Start an Activity from Splash Screen, should I use run() or runOnUiThread()?

I have a Splash Screen (Logo Activity) to show the company name for 3 seconds before app starts. I start Main Activity from a thread, here is the code:

public class Logo extends Activity {

Thread t;
public boolean dead = false;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logo);

    t = new Thread() {
        public void run() {
            try {
                Intent i = new Intent(Logo.this, Main.class);
                Thread.sleep(3000);
                if (!dead) {
                    startActivity(i);
                }
                finish();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}

The Main Activity is called from a worked thread, is this correct? What are the differents with this code (using runOnUiThread )?

...
if (!dead) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
           Intent i = new Intent(Logo.this, Main.class);
           startActivity(i);
        }
    });
}
...

I see no difference with this code in debug mode (The same threads, the same operation, etc.). Which is correct?

Starting an intent I think is not an UI operation. runOnUI thread runs UI operation on UI thread. So you can use either of thread (runOnUI or normal). May be normal thread will be good in this situation. But I would like to suggest you use timer instead.

To be honest, I don't like the Thread.sleep. PLease take a look at my solution:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
      // Do your work here like... startActivity...
    }
}, SPLASH_DURATION); // SPLASH_DURATION IS IN MILLISECONDS LIKE 3000

Also you can block the user to prevent the back key like this:

@Override
public void onBackPressed() {
    // do nothing! disable user interaction!
}

You should use AsyncTask in "doInBackground" background thread and than sleep your thread(this thread not UIThread) "PostExecute" run on UI Thread than start your new activity

private class mSplashViewer extends AsyncTask<Void,Void,Void>{

 protected void doInBackground(Void params){

   Thread.currentThread().sleep(3000);
   return null;
 }

 protected void onPostExecute(){
  startActivity(...);
 }

}

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