Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, Handler is running in main thread or other thread?

I have following code.

public class SplashScreen extends Activity {
    private int _splashTime = 5000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                 WindowManager.LayoutParams.FLAG_FULLSCREEN);

        new Handler().postDelayed(new Thread(){
           @Override
           public void run(){
             Intent mainMenu = new Intent(SplashScreen.this, MainMenu.class);
             SplashScreen.this.startActivity(mainMenu);
             SplashScreen.this.finish();
             overridePendingTransition(R.drawable.fadein, R.drawable.fadeout);
           }
        }, _splashTime);
    }
}

I have problem in analyze of this code. As far as know handler is running in main thread. but it has thread which is running in other thread.

MainMenu.class will be run in main thread or second thread? if main thread is stopped for 5 seconds ANR will be raise. Why when I am stopping it with delay (_splashTime) ANR doesn't display (even if i increase it to more than 5 seconds)

like image 559
Hesam Avatar asked Oct 27 '12 08:10

Hesam


1 Answers

As far as know handler is running in main thread.

Objects do not run on threads, because objects do not run. Methods run.

but it has thread which is running in other thread.

You have not posted any code which involves any "other thread". Everything in the code listing above is tied to the main application thread of your process.

MainMenu.class will be run in main thread or second thread?

Objects do not run on threads, because objects do not run. Methods run. MainMenu appears to be an Activity. The activity lifecycle methods (e.g., onCreate()) are called on the main application thread.

Why when I am stopping it with delay (_splashTime) ANR doesn't display (even if i increase it to more than 5 seconds)

You are not "stopping [the main application thread] with delay". You have scheduled a Runnable to be run on the main application thread after a delay _splashTime milliseconds. However, postDelayed() is not a blocking call. It simply puts an event on the event queue that will not be executed for _splashTime milliseconds.

Also, please replace Thread with Runnable, since postDelayed() does not use Thread. Your code compiles and runs, because Thread implements Runnable, but you will confuse yourself by thinking that using Thread instead of Runnable means that your code will run on a background thread, and it will not.

like image 160
CommonsWare Avatar answered Oct 19 '22 14:10

CommonsWare