Skip to content

Instantly share code, notes, and snippets.

@pokk
Created May 11, 2017 10:13
Show Gist options
  • Save pokk/801cf2ae8a4e01aa69cf8e04abf178c4 to your computer and use it in GitHub Desktop.
Save pokk/801cf2ae8a4e01aa69cf8e04abf178c4 to your computer and use it in GitHub Desktop.
Android run on the new thread.

Introduction

Thread category in Android.

Java

  • Thread
  • Handler
  • AsyncTask
  • IntentService
  • ThreadPoolExecutor

Kotlin

  • Concurrent

Common Problem

Using a simple handle on your activity or fragment.

Handler().post {
    // Here won't be a new thread. This thread is running on the UI thread.
}
handler=new Handler();
handler.post(new Runnable(){
  void run(){
        // The same as above.
  }
});

You can use it as like this way.

How to create a new thread

Here is Kotlin code.

// Thread
Thread {
    // Here will create a new thread.
}.start()

// HandlerThread
HandlerThread("string") {
    // Here will create a new thread.
}.start()

// Concurrent
thread {
    // Here will create a new thread.
}

Here is Java code.

// Thread
Thread thread = new Thread();
thread.start();

// HandlerThread
HandlerThread thread = new HandlerThread("string");
thread.start();

About Looper

The code as the above, you can figure out that they are running on the mainThread(UIThread). Of course, you can also define a new Looper.

new Thread(new Runnable() {
    public void run() {
        Looper.prepare();

        new Handler().post(new Runnable(){
            @Override
            public void run() {
                Log.e(TAG, "B1");
            }
        });

        new Handler().post(new Runnable(){
            @Override
            public void run() {
                Log.e(TAG, "B2");
                Looper.myLooper().quit();
            }
        });

        Looper.loop();

        Log.e(TAG, "C");
        ((Activity) mContext).runOnUiThread(new Runnable() {
            public void run() {
                Log.e(TAG, "D");
            }
        });
    }
}).start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment