Thread
category in Android.
Java
- Thread
- Handler
- AsyncTask
- IntentService
- ThreadPoolExecutor
Kotlin
- Concurrent
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.
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();
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();