LoginSignup
6
6

More than 5 years have passed since last update.

[Android] HandlerとHandlerThreadでキュー管理

Posted at

UIスレッドで実行したい処理をキューで管理したい場合は、下記のコードで

Handler
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            // UIスレッド(スレッド名は[main])で実行される
        }
    });
}

UIスレッド以外で実行した処理をキューで管理したい場合は、以下のコードで

HandlerThread
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    HandlerThread handlerThread = new HandlerThread("other");
    handlerThread.start();

    // HandlerThreadを予めstart()させておかないとgetLooper()でnullが返却される

    Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            // ワーカスレッド(スレッド名は[other])で実行される
        }
    });
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6