簡體   English   中英

Android,Handler是在主線程還是其他線程中運行?

[英]Android, Handler is running in main thread or other thread?

我有以下代碼。

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);
    }
}

我在分析這段代碼時遇到了問題。 至於知道處理程序在主線程中運行。 但它有在其他線程中運行的線程。

MainMenu.class將在主線程或第二個線程中運行? 如果主線程停止5秒,ANR將被提升。 為什么我延遲停止它(_splashTime) ANR不顯示(即使我將它增加到超過5秒)

至於知道處理程序在主線程中運行。

對象不在線程上運行,因為對象不運行。 方法運行。

但它有在其他線程中運行的線程。

您尚未發布涉及任何“其他線程”的任何代碼。 上面代碼清單中的所有內容都與流程的主應用程序線程相關聯。

MainMenu.class將在主線程或第二個線程中運行?

對象不在線程上運行,因為對象不運行。 方法運行。 MainMenu似乎是一個Activity 在主應用程序線程上調用活動生命周期方法(例如, onCreate() )。

為什么我延遲停止它(_splashTime)ANR不顯示(即使我將它增加到超過5秒)

你不是“延遲[主應用程序線程]”。 您已安排在延遲_splashTime毫秒后在主應用程序線程上運行Runnable 但是, postDelayed()不是阻塞調用。 它只是在事件隊列上放置一個事件,該事件將不會在_splashTime毫秒內執行。

另外,請用Runnable替換Thread ,因為postDelayed()不使用Thread 你的代碼編譯並運行,因為Thread實現了Runnable ,但你會因為認為使用Thread而不是Runnable意味着你的代碼將在后台線程上運行而不會。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM