#handlerthread
Explore tagged Tumblr posts
intellisourcetechnology · 5 months ago
Text
Must-Know Tips for Achieving Greater Android App Performance
In Android application development it is highly important for the responsiveness of the application. Intensive programs slow the machine down and even when they respond their response time is slow, which contributes to high uninstall rates and user turnover.
Hence, it is crucial to know how to enhance Android App performance. For instance, if you are an Android development expert, or you contracted Android App Development Company Florida, it is crucial to learn more about the appropriate measures of boosting the application’s performance.
Optimize Layouts and Views
Among the significant factors influencing the performance of the Android application, are the optimized layouts and views in the first place. Complicated designs always result in more time taken to load a page than simple ones given the low-capable devices present in the market today.
In order to highly optimize layouts one should not nest layouts unless it is extremely necessary. Still, you are recommended to use ConstraintLayout and RelativeLayout as these layouts help to minimize the view hierarchy depth and, consequently, maximize performance.
Efficient Resource Management
This paper seeks to establish that, resource management is a critical factor that defines Android App Performance. When an app has high resource utilization it implies that your CPU, memory, or battery will be consumed thus the performance will drop, battery will drain faster.
Because the background processes and services consume battery life and if not managed properly might cause the app to become unresponsive, limit the background processes and services that your app launches. Use Android’s JobScheduler/ WorkManager to handle background operations more efficiently.
Implement Lazy Loading
This is a method of loading images or processes which where they are only loaded when required. The immediate loading of all data causes a greater load on system resources, hence, by only loading content as the user scrolls, utilizes system resources sparingly making the app more responsive with less initial loading time.
For instance, when using list view instead of loading the entire list it is possible to load only the current list and other lists as the user scrolls through the list.
Minimize Main Thread Operations
The thread that truly is in charge of the application, or the 'main thread,' is responsible for processing anything having to do with the user interface and updating view elements. If many heavy requests (network requests, complex mathematical calculations, and big file processing) are initiated in the main thread, the app hangs or freezes.
, AsyncTask, HandlerThread, and modern Kotlin Coroutines are some of the ways that can be used to perform other tasks in the background while making the UI thread remain unblocked.
Leverage Caching
Here, it is also important to take a look at Caching as an important measure of enhancing the performance of Android apps. Since the data that is frequently used can be temporarily stored in it, there are less frequent requests for the network or database.
Use DiskLruCache, SharedPreferences, or SQLite for data caching locally, although it is recommended that you combine DiskLruCache and SharedPreferences or SQLite. This not only increases the object's loading and speed but also decreases the probability of network traffic saturation.
For images, there are libraries called Glide and Picasso that will actually cache images so that the time is also saved on getting images from the network.
Optimize Network Requests
Network requests are one of the most troublesome sources of performance problems in the case of apps employing them. Another way is to think about how to decrease the number of requests sent to minimize the impact of the network latency By combining a number of requests to 'batch', or using a multiplexed TCP connection such as HTTP/2.
When it comes to such requests as network, the reader is advised to use Retrofit or OkHttp for request handling and you can also try using GZIP for the size of data.
Monitor and Reduce App Startup Time
The time taken by an application to start is among the few crucial factors that define user satisfaction. Long startup times also mean that users are discouraged from even launching your application in the first place. To enhance the Android App Performance, one should aim at reducing the work that is to be done during the initialization phase.
This means that one can delay certain operations until the time when the essential elements have been loaded to the app's main screen. To manage time in loading only the most important components and do it with the help of Android's Startup Library.
Reduce APK Size
The size of your app is heavily important because a bigger size may affect the download and installation time and after that the loading time of the overall application. This is important to the user who’ll be downloading the APK on slow networks or limited space on their devices.
There are three ways of reducing APK size these include, elimination of any resource that is not wanted, optimization of images, and finally shrinking and obfuscation of the code through the use of Proguard or R8.
Adopt Modern Android Development Tools
If the Android App Performance has to be optimized then techniques of modern development tools available help in doing this job much more efficiently. There are several other tools available that can be used to monitor the real time performances of an Android application.
These include the Android Profiler and LeakCanary for memory, CPU, and other usage metrics. They assist you to diagnose and eliminate performance issues promptly. You can also check top app development platform.
Regularly Test and Monitor Performance
Last but not least often it is pertinent to examine and assess Android App Performance on a frequent basis in the Development Cycle. Firebase has features such as Performance Monitoring, through which you can monitor how the application performs on real devices. Especially when the network connection is slow or non-existent and the device is not fully capable of meeting your application demands.
Android App Performance Optimization is one of the most important factors that dictate how an app will perform in order to enhance the interactive lifestyle of the user. If you follow the above guidelines — getting layouts right, managing resources to adopting the use of brand-new development tools, your app will perform well.
For any firm that is interested in enhancing the performance of the app, or any organization that requires the services, it is advisable to hire the services of the best Android App Development Company Florida.
0 notes
jacob-cs · 7 years ago
Text
bounds service
activity, service 등등 ( components )와 연결된 service를 bounds service라고 한다.
구현방법에따라 세가지로 구분할수 있다. 
1. Binder class를 이용하는 경우 
2. Messenger를 이용하는 경우
3. AIDL를 이용하는 경우
구현방법에따른 구분이이지만 사용용도 조금다르다. Binder를 이용하는 경우는 같은 application , process내의 components와 service간의 연결에 사용한다. Messenger와 AIDL은 다른 application간에도 서로 연결, 상호작업애 사용된다. 즉 interprocess communication (IPC)에 사용될수 있다.
참고사항)
Messenger를 사용하는 방법에는 Handler, message를 이용하는데 이는 HandlerThread에서도 사용된다. looper, handler, message를 이용하는데 bound service와도 조금의 연관성을 찾을수 있다. HandlerThread는 big bernard android programming 책을 참조하거나 내가 모은 tumblr자료를 검색한다. HandlerThread를 이용한 간단한 예시로 flickr에서 여러개의 image를 main thread가아닌 다른 thread에서 fetch하는 작업
handlerthread를 설명한 동영상 시리즈
-handlerthread없이 thread로 같은 기능을 구현하는 과정을 보여준다.
https://www.youtube.com/watch?v=rfLMwbOKLRk
https://youtu.be/Yo3VT-fZr68
-handlerthread를 이용한 것을 보여준다.
https://youtu.be/998tPb10DFM
개념 , 사용방법 설명 문서
https://stuff.mit.edu/afs/sipb/project/android/docs/guide/components/bound-services.html 
사용방법 동영상 ( Binder를 이용한방법 )
예시작업으로 activity에 bound된 service에 있는 현재시간을 계산하는 함수를 activity에서 호출해서 값을 가져오는 과정으로 들었다.
https://youtu.be/0c4jRCm353c
https://youtu.be/zCj5Qzzex_A
0 notes
hgsummerofcode · 2 years ago
Text
This blog is not dead!
I have been keeping true to my word and working on my Antidote android app. It's slow going because android is a nightmare to develop for (but it's the phone I and the majority of my friends use). Also, I haven't posted many updates because there's no visual component to it yet.
So far, I've been able to make an android activity that connects via socket to a python server that I made with this tutorial: https://realpython.com/python-sockets/ . I was going back and forth about using HTTP or just doing my own data encoding but HTTP gives me a headache when I use it for anything other than web pages. I'm sure there's a better way to do what I'm doing with HTTP but uh. I'll figure that out later. Right now I'm focused on making it work and then I'll make it better.
I'm still struggling with step 1 though lol. I did make a connection that sends a "Hello world" message and then closes, but I'm setting the Android project up to be able to maintain a single connection and send multiple messages back and forth through it. I have the main activity (right now it's just a button that says connect), a service that can run in the background and handles all the game logic, and a HandlerThread that runs the socket connection. I spent all of my winter break getting here lol and it feels like I haven't actually accomplished anything. I have successfully bound the activity to the service and created the network thread, so my next tasks are being able to send messages to the server, interpret messages from the server, and close the connection.
I have one more weekend until my Spring classes start. I'm hoping I can get something done before then!
0 notes
presbus · 7 years ago
Text
Threading With HandlerThread in Android
Threading With HandlerThread in Android
[ad_1]
Responsiveness is one of the most valuable features of any app. This is even more important in resource-constrained devices like smartphones. Users must be able to interact with the app in a smooth way without falling into flickering or a slow UI. For these reasons, concurrent programming must now be a part of the skillset of every developer.
It’s very important to know that all the…
View On WordPress
0 notes
iyarpage · 7 years ago
Text
Threading With HandlerThread in Android [FREE]
You will learn how to use HandlerThread to receive messages from a Runnable in an Activity and pass them back to a UI handler to update the UI. Threading With HandlerThread in Android [FREE] published first on https://medium.com/@koresol
0 notes
cdemiranda · 7 years ago
Link
via Ray Wenderlich
0 notes
night-finance-site-blog · 8 years ago
Text
ハンドラ生成
uiHandler = new Handler();
MandlerThread thread = new Handler Thread(”work”);
workHandler = new Handler(thread.getLooper());
HandlerThread(String name)
Looper getLooper()
0 notes
jacob-cs · 7 years ago
Link
original source : https://riptutorial.com/android/example/5182/handlerthreads-and-communication-between-threads
Example
As Handlers are used to send Messages and Runnables to a Thread's message queue it's easy to implement event based communication between multiple Threads. Every Thread that has a Looper is able to receive and process messages. A HandlerThread is a Thread that implements such a Looper, for example the main Thread (UI Thread) implements the features of a HandlerThread.
Creating a Handler for the current Thread
Handler handler = new Handler();
Creating a Handler for the main Thread (UI Thread)
Handler handler = new Handler(Looper.getMainLooper());
Send a Runnable from another Thread to the main Thread
new Thread(new Runnable() {    public void run() {        // this is executed on another Thread        // create a Handler associated with the main Thread        Handler handler = new Handler(Looper.getMainLooper());        // post a Runnable to the main Thread        handler.post(new Runnable() {            public void run() {                // this is executed on the main Thread            }        });    } }).start();
Creating a Handler for another HandlerThread and sending events to it
// create another Thread HandlerThread otherThread = new HandlerThread("name"); // create a Handler associated with the other Thread Handler handler = new Handler(otherThread.getLooper()); // post an event to the other Thread handler.post(new Runnable() {    public void run() {        // this is executed on the other Thread    } });
0 notes
jacob-cs · 7 years ago
Link
original source : https://stackoverflow.com/questions/12877944/what-is-the-relationship-between-looper-handler-and-messagequeue-in-android
android handlerthread, looper, handler 개념잡기 좋은 내용
A Looper is a message handling loop: it reads and processes items from a MessageQueue. The Looper class is usually used in conjunction with a HandlerThread (a subclass of Thread).
A Handler is a utility class that facilitates interacting with a Looper—mainly by posting messages and Runnable objects to the thread's MessageQueue. When a Handler is created, it is bound to a specific Looper (and associated thread and message queue).
In typical usage, you create and start a HandlerThread, then create a Handler object (or objects) by which other threads can interact with the HandlerThread instance. The Handler must be created while running on the HandlerThread, although once created there is no restriction on what threads can use the Handler's scheduling methods (post(Runnable), etc.)
The main thread (a.k.a. UI thread) in an Android application is set up as a handler thread before your application instance is created.
Aside from the class docs, there's a nice discussion of all of this here.
It's widely known that it's illegal to update UI components directly from threads other than main thread in android. This android document (Handling Expensive Operations in the UI Thread) suggests the steps to follow if we need to start a separate thread to do some expensive work and update UI after it's done. The idea is to create a Handler object associated with main thread, and post a Runnable to it at appropriate time. This Runnable will be invoked on the main thread. This mechanism is implemented with Looper and Handler classes.
The Looper class maintains a MessageQueue, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created. This association is kept forever and can't be broken nor changed. Also note that a thread can't be associated with more than one Looper. In order to guarantee this association, Looper is stored in thread-local storage, and it can't be created via its constructor directly. The only way to create it is to call prepare static method on Looper. prepare method first examines ThreadLocal of current thread to make sure that there isn't already a Looper associated with the thread. After the examination, a new Looper is created and saved in ThreadLocal. Having prepared the Looper, we can call loop method on it to check for new messages and have Handler to deal with them.
As the name indicates, the Handler class is mainly responsible for handling (adding, removing, dispatching) messages of current thread's MessageQueue. A Handler instance is also bound to a thread. The binding between Handler and Thread is achieved via Looper and MessageQueue. A Handler is always bound to a Looper, and subsequently bound to the thread associated with the Looper. Unlike Looper, multiple Handler instances can be bound to the same thread. Whenever we call post or any methods alike on the Handler, a new message is added to the associated MessageQueue. The target field of the message is set to current Handler instance. When the Looper received this message, it invokes dispatchMessage on message's target field, so that the message routes back to to the Handler instance to be handled, but on the correct thread. The relationships between Looper, Handler and MessageQueue is shown below:
Let's start with the Looper. You can understand the relationship between Looper, Handler and MessageQueue more easily when you understand what Looper is. Also you can better understand what Looper is in the context of GUI framework. Looper is made to do 2 things.
1) Looper transforms a normal thread, which terminates when its run() method returns, into something that runs continuously until Android app is running, which is needed in GUI framework (Technically, it still terminates when run() method returns. But let me clarify what I mean, below).
2) Looper provides a queue where jobs to be done are enqueued, which is also needed in GUI framework.
As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not some secret, special thread. It's just a normal thread that you can also create with new Thread() code, which means it terminates when its run() method returns! Think of below example.
0 notes
jacob-cs · 8 years ago
Link
original source : http://stackoverflow.com/questions/23114656/difference-between-android-looper-and-executor-thread-pool
A Looper manages tasks that a Thread will run. It puts them in a queue and then the Thread takes the next task in line. A Looper is tied to a specific Thread.
An Executor encapsulates managing and distributing tasks to different Threads. If you have a fixed threadpool size of 1 then I suppose it would be similar in design to a Looper because it will just queue up the work for that one Thread. If you have a threadpool with size > 1 then it will manage giving the task to the next Thread available to do the work, or in other words it will distribute tasks among all threads.
edit: Recommended reading: http://developer.android.com/reference/java/util/concurrent/package-summary.html
Executors are more flexible. For Android, the only time I really use Looper is when trying to make a Handler to communicate with the main thread from a background thread (which could even be in an ExecutorService). For example:
Handler mainThreadHandler = new Handler(Looper.getMainLooper()); mainThreadHandler.post(new Runnable...); //runs on main thread
0 notes
jacob-cs · 8 years ago
Link
original source : https://blog.mindorks.com/android-core-looper-handler-and-handlerthread-bd54d69fe91a
참고자료 : https://stackoverflow.com/questions/12877944/what-is-the-relationship-between-looper-handler-and-messagequeue-in-android
A Looper is a message handling loop: it reads and processes items from a MessageQueue. The Looper class is usually used in conjunction with a HandlerThread (a subclass of Thread).
A Handler is a utility class that facilitates interacting with a Looper—mainly by posting messages and Runnable objects to the thread's MessageQueue. When a Handler is created, it is bound to a specific Looper (and associated thread and message queue).
In typical usage, you create and start a HandlerThread, then create a Handler object (or objects) by which other threads can interact with the HandlerThread instance. The Handler must be created while running on the HandlerThread, although once created there is no restriction on what threads can use the Handler's scheduling methods (post(Runnable), etc.)
The main thread (a.k.a. UI thread) in an Android application is set up as a handler thread before your application instance is created.
Aside from the class docs, there's a nice discussion of all of this here.
It's widely known that it's illegal to update UI components directly from threads other than main thread in android. This android document (Handling Expensive Operations in the UI Thread) suggests the steps to follow if we need to start a separate thread to do some expensive work and update UI after it's done. The idea is to create a Handler object associated with main thread, and post a Runnable to it at appropriate time. This Runnable will be invoked on the main thread. This mechanism is implemented with Looper and Handler classes.
The Looper class maintains a MessageQueue, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created. This association is kept forever and can't be broken nor changed. Also note that a thread can't be associated with more than one Looper. In order to guarantee this association, Looper is stored in thread-local storage, and it can't be created via its constructor directly. The only way to create it is to call prepare static method on Looper. prepare method first examines ThreadLocal of current thread to make sure that there isn't already a Looper associated with the thread. After the examination, a new Looper is created and saved in ThreadLocal. Having prepared the Looper, we can call loop method on it to check for new messages and have Handler to deal with them.
As the name indicates, the Handler class is mainly responsible for handling (adding, removing, dispatching) messages of current thread's MessageQueue. A Handler instance is also bound to a thread. The binding between Handler and Thread is achieved via Looper and MessageQueue. A Handler is always bound to a Looper, and subsequently bound to the thread associated with the Looper. Unlike Looper, multiple Handler instances can be bound to the same thread. Whenever we call post or any methods alike on the Handler, a new message is added to the associated MessageQueue. The target field of the message is set to current Handler instance. When the Looper received this message, it invokes dispatchMessage on message's target field, so that the message routes back to to the Handler instance to be handled, but on the correct thread. The relationships between Looper, Handler and MessageQueue is shown below:
Let's start with the Looper. You can understand the relationship between Looper, Handler and MessageQueue more easily when you understand what Looper is. Also you can better understand what Looper is in the context of GUI framework. Looper is made to do 2 things.
1) Looper transforms a normal thread, which terminates when its run() method returns, into something that runs continuously until Android app is running, which is needed in GUI framework (Technically, it still terminates when run() method returns. But let me clarify what I mean, below).
2) Looper provides a queue where jobs to be done are enqueued, which is also needed in GUI framework.
As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not some secret, special thread. It's just a normal thread that you can also create with new Thread() code, which means it terminates when its run() method returns! Think of below example.
This Article covers Android Looper, Handler, and HandlerThread. These are among the building blocks of Android OS.
In my own experience, I have used them in a very limited context until recently. My use case involved sending tasks to the main/ui thread, primarily to update the UI from any other thread. The other aspects of the multi-threaded operation were handled through alternate ways like ThreadPoolExecutor, IntentService, and AsyncTask.
MultiThreading and task running are old subjects. Java itself has java.util.concurrent package and Fork/Join framework to facilitate it. Several libraries have been written to streamline asynchronous operations. RxJava is the most popular library today for reactive programming and designing an asynchronous application.
So, why am I writing about the old school?
Looper, Handler, and HandlerThread are the Android’s way of solving the problems of asynchronous programming. They are not old school, but a neat structure on which a complex android framework is built.
For new developers, it’s highly recommended to understand the principles behind them and experienced one’s should revisit this topic to recollect the minor details.
Use Cases:
The main thread in Android is built with a Looper and Handlers. So, the understanding of it is essential to create an unblocked responsive UI.
The developers writing libraries cannot afford to use third party libraries because of the library size. So, for them, the best option is to utilize the existing available resource. Writing own solution for it may not always get that level of efficiency and optimization.
The same argument can also be made for companies/individuals shipping out SDKs. The clients can have varied implementations, but all of them will share the common android framework APIs.
Understanding them fully will enhance the capacity to follow the Android SDK and package classes in general.
Let’s start the exploration/revision with a questionnaire.
I expect the reader to have the basic understanding of java threads. If you need, then get a quick overview of java Thread and Runnable.
What is the problem with java thread?
Java threads are one-time use only and die after executing its run method.
Can we improve upon it?
The Thread is a double edged sword. We can speed up the execution by distributing the tasks among threads of execution, but can also slow it down when threads are in excess. Thread creation in itself is an overhead. So, the best option is to have an optimum number of threads and reuse them for tasks execution.
Model for thread reusability:
The thread is kept alive, in a loop via it’s run() method.
The task is executed serially by that thread and is maintained in a queue (MessageQueue).
The thread must be terminated when done.
What is the Android’s way of doing it?
The above model is implemented in the Android via Looper, Handler, and HandlerThread. The System can be visualized to be a vehicle as in the article’s cover.
MessageQueue is a queue that has tasks called messages which should be processed.
Handler enqueues task in the MessageQueue using Looper and also executes them when the task comes out of the MessageQueue.
Looper is a worker that keeps a thread alive, loops through MessageQueue and sends messages to the corresponding handler to process.
Finally Thread gets terminated by calling Looper’s quit() method.
One thread can have only one unique Looper and can have many unique Handlers associated with it.
Creating Looper and MessageQueue for a Thread:
A thread gets a Looper and MessageQueue by calling Looper.prepare() after its running. Looper.prepare() identifies the calling thread, creates a Looperand MessageQueue object and associate the thread with them in ThreadLocal storage class. Looper.loop() must be called to start the associated looper. Similarly, the looper must be terminated explicitly through looper.quit().
class LooperThread extends Thread {      public Handler mHandler;      public void run() {          Looper.prepare();          mHandler = new Handler() {              public void handleMessage(Message msg) {                 // process incoming messages here                 // this will run in non-ui/background thread              }          };          Looper.loop();      }  }
Creating Handler for a Thread:
A Handler gets implicitly associated with the thread that instantiates it via thread’s Looper, but we can explicitly tie it to a thread by passing the thread’s looper in the constructor of the Handler.
handler = new Handler() {    @Override    public void handleMessage(Message msg) {        // process incoming messages here        // this will run in the thread, which instantiates it    } };
Sending messages to the MessageQueue via Handler can be done by two modes:
Message: It is a class that defines various useful methods to deal with message data. To send an object we set the obj variable.
Message msg = new Message(); msg.obj = "Ali send message"; handler.sendMessage(msg);
Detailed overview of Message class can be found here: https://developer.android.com/reference/android/os/Message.html
2. Runnable: A runnable can also be posted in the MessageQueue. Ex: posting and running a task in the main thread.
new Handler(Looper.getMainLooper()).post(new Runnable() {    @Override    public void run() {        // this will run in the main thread    } });
In the above example, we create a Handler and provide Looper associated with the main thread. This associate this handler to the main thread. When we post the Runnable, it gets queued in the main thread’s MessageQueue and then executed in the main thread.
Handler is capable of message manipulation in a wide variety of ways, which can found here: https://developer.android.com/reference/android/os/Handler.html
Creating an own thread and providing Lopper and MessageQueue is not the right way to deal with the problem. So, Android has provided HandlerThread (subclass of Thread) to streamline the process. Internally it does the same things that we have done but in a robust way. So, always use HandlerThread.
One of the ways to create the HandlerThread is to subclass it and most of the time you will be using this method.
private class MyHandlerThread extends HandlerThread {    Handler handler;    public MyHandlerThread(String name) {        super(name);    }    @Override    protected void onLooperPrepared() {        handler = new Handler(getLooper()) {            @Override            public void handleMessage(Message msg) {                // process incoming messages here                // this will run in non-ui/background thread            }        };    } }
Note: We have instantiated the Handler when the onLooperPrepared() is called. So, that Handler can be associated with that Looper.
Looper is only prepared after HandlerThread’s start() is called i.e. after the thread is running.
A Handler can be associated with a HandlerThread, only after it’s Looper is prepared.
Other way to create the HandlerThread:
HandlerThread handlerThread = new HandlerThread("MyHandlerThread"); handlerThread.start(); Handler handler = new Handler(handlerThread.getLooper());
Note: HandlerThread needs to call myHandlerThread.quit() to free the resources and stop the execution of the thread.
I would suggest practicing the above codes, so you can grasp their little details.
I have created an example project for Post Office simulation. Post Office is built upon HandlerThread and Clients communicate with the help of the Post Office. A Simulator class creates few Client Bots and delegate their communication to the MainActivity, which renders it in a live feed.
The link to this Example:
MindorksOpenSource/post-office-simulator-looper-example post-office-simulator-looper-example - This Android project simulates a Post Office using HandlerThreadgithub.com
Thanks for reading this article. Be sure to click ❤ below to recommend this article if you found it helpful. It would let others get this article in search and spread the knowledge.
For more about programming, follow me and Mindorks, so you’ll get notified when we write new posts.
Check out all the Mindorks best articles here.
Coder’s Rock :)
0 notes
jacob-cs · 8 years ago
Link
original source: http://stackoverflow.com/questions/7597742/what-is-the-purpose-of-looper-and-how-to-use-it
What is Looper?
Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).
Where we can use Looper class?
If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.
How it works?
There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.
Here is the code by which you can prepare the Looper.
class LooperThread extends Thread {      public Handler mHandler;      @Override      public void run() {          Looper.prepare();          mHandler = new Handler() {              @Override              public void handleMessage(Message msg) {                  // process incoming messages here              }          };          Looper.loop();      }  }
You can better understand what Looper is in the context of GUI framework. Looper is made to do 2 things.
1) Looper transforms a normal thread, which terminates when its run() method return, into something run continuously until Android app is running, which is needed in GUI framework (Technically, it still terminates when run() method return. But let me clarify what I mean in below).
2) Looper provides a queue where jobs to be done are enqueued, which is also needed in GUI framework.
As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not some secret, special thread. It's just a normal thread that you can also create with new Thread() code, which means it terminates when its run() method return! Think of below example.
public class HelloRunnable implements Runnable {    public void run() {        System.out.println("Hello from a thread!");    }    public static void main(String args[]) {        (new Thread(new HelloRunnable())).start();    } }
Now, let's apply this simple principle to Android app. What would happen if an Android app runs on normal thread? A thread called "main" or "UI" or whatever starts your application, and draws all UI. So, the first screen is displayed to users. So what now? The main thread terminates? No, it shouldn’t. It should wait until users do something, right? But how can we achieve this behavior? Well, we can try with Object.wait() or Thread.sleep(). For example, main thread finishes its initial job to display first screen, and sleeps. It awakes, which means interrupted, when a new job to do is fetched. So far so good, but at this moment we need a queue-like data structure to hold multiple jobs. Think about a case when a user touches screen serially, and a task takes longer time to finish. So, we need to have a data structure to hold jobs to be done in first-in-first-out manner. Also, you may imagine, implementing ever-running-and-process-job-when-arrived thread using interrupt is not easy, and leads to complex and often unmaintainable code. We'd rather create a new mechanism for such purpose, and that is what Looper is all about. The official document of Looper class says, "Threads by default do not have a message loop associated with them", and Looper is a class "used to run a message loop for a thread". Now you can understand what it means.
To make things more clear, let's check the code where main thread is transformed. It all happens in ActivityThread class. In its main() method, you can find below code, which turns a normal main thread into something what we need.
public final class ActivityThread {    ...    public static void main(String[] args) {        ...        Looper.prepareMainLooper();        Looper.loop();        ...    } }
and Looper.loop() method loop infinitely and dequeue a message and process one at a time:
public static void loop() {    ...    for (;;) {        Message msg = queue.next(); // might block        if (msg == null) {            // No message indicates that the message queue is quitting.            return;        }        ...        msg.target.dispatchMessage(msg);        ...    } }
So, basically Looper is a class that is made to address a problem that occurs in GUI framework. But this kind of needs also can happen in other situation as well. Actually it is a pretty famous pattern for multi threads application, and you can learn more about it in "Concurrent Programming in Java" by Doug Lea(Especially, chapter 4.1.4 "Worker Threads" would be helpful). Also, you can imagine this kind of mechanism is not unique in Android framework, but all GUI framework may need somewhat similar to this. You can find almost same mechanism in Java Swing framework.
0 notes
jacob-cs · 8 years ago
Link
original source : https://medium.com/@ali.muzaffar/handlerthreads-and-why-you-should-be-using-them-in-your-android-apps-dc8bf1540341
This was my first and last encounter with them for a while. It seemed like a very low level API and something that may not necessarily be meant to be used by app developers. I had rarely (almost never) seen it used in any code sample for how to do perform asynchronous tasks in Android. I did mentioned them as a way to do asynchronous processing in my article 8 ways to do asynchronous processing in Android and counting, even there, I deferred to just regular Theads and ignored how HandlerThreads are used.
It wasn't till a recent conversation with Colt McAnlis at the BABBQ15 that I heard the mentions of HandlerThreads again. The difference this time was that they were in context of how they process commands from a queue and how this makes for situations where you have to perform a lot of asynchronous tasks. This sounded like just about every application I have written, so why weren't these mentioned more readily in Android Development literature?
Since the BABBQ, I’ve looked some into HandlerThreads and from what I figure, there are 2 main reasons why developers/educators may be inclined to not mention HandlerThreads.
HandlerThreads run outside of your activity’s lifecycle, so they need to be cleaned up properly or else you will have thread leaks. This is especially dangerous if you are using them for long running processes. I recall Colt mentioning (I may be wrong) that you can have HandlerThreads with a timeout, so if they haven’t processed anything from the queue in a while, they should terminate themselves. I haven’t been able to find any way of doing this, short of extending HandlerThreads and adding the functionality myself. Update: HandlerThread doesn’t have a time out, a ThreadpoolExecutor has a timeout that can be used to wind down unused threads.
There is no convenient mechanism for posting results back to the main thread. This means more boilerplate code.
What is the problem with AsyncTask
AsyncTasks have a single thread dedicated to them, so if you spin off more than one AsyncTask, they aren’t truly asynchronous. This is not necessarily a problem, but it is restrictive if you do want multiple threads. With each AsyncTask that is spun off, a thread is created and destroyed which, if you have a lot of AsyncTasks is a performance issue.
What is wrong with Service
Services are executed on the main thread, so they aren't really asynchronous. You have to create a separate thread for them to use if you want them to be asynchronous. With both of these you still have a new thread being created and destroyed.
Why not use IntentService
As Ian Lake points out (link to discussion on Google+), IntentService does use HandlerThread internally (link to source) and this does make them a great option to use. He also points out that there is ever only one instance of a Service in existence at any given time and it has only one HandlerThread. This means that if you need more than one thing to happen at the same time, IntentServices may not be a good option. However, looking at the source for the IntentService, it does illustrate that the techniques discussed below are in fact used within the Android SDK itself and as such it is a design pattern you should be familiar with.
How do I use HandlerThreads
There are 2 main ways that I found to use HandlerThreads.
Create a new HandlerThread, create a new Handler using this HandlerThread and post your tasks on this handler.
Extend HandlerThread inside your CustomHandlerThread, create a Handler to process your task. You would take this approach if you know the task you want to perform and just need to pass in parameters. An example would be creating a HandlerThread to download images or perform networking operations.
Implementation of HandlerThread
The implementation is very straight forward.
HandlerThread handlerThread = new HandlerThread("MyHandlerThread"); handlerThread.start(); Looper looper = handlerThread.getLooper(); Handler handler = new Handler(looper);
As I mentioned earlier, we create a new HandlerThread and give it any name. We then start the HandlerThread, get the Looper for the HandlerThread and pass it to a handler.
Then, in order to use it, you simply have to post Runnable to the Handler thread.
handler.post(new Runnable(){…});
If you have a few different tasks you would like to perform on the background thread, it may be a better idea to extend handler and adding handling for different messages. Note, there is still one background thread here. If you want more threads, you’ll have to create more Handlers and HandlerThreads.
if (mHandler == null) {    mHandler = new Handler(looper) {        @Override        public void handleMessage(Message msg) {            switch (msg.what) {                case SOMETHING_ACTION: {                    doSomething();                    break;                }                case SOMETHING_ELSE_ACTION:                    doMoreThings();                    break;                default:                    break;            }        }    }; } //usage mHandler.obtainMessage(SOMETHING_ACTION, ""); mHandler.sendMessage(msg);
IMPORTANT: Remember to call handlerThread.quit() when you are done with the background thread or on your activities onDestroy() method.
As you can see, Option 1 is probably best suited in situations where you don’t have a lot of code. I haven’t covered the scenario of posting back the result to the main thread either.
Posting back the results to the UI thread
There are two approaches that are best used here. You can either make a LocalBroadcast with the result:
Intent in = new Intent(DO_SOMETHING_RESULT); in.putExtra(DO_SOMETHING_RESULT, result); LocalBroadcastManager.getInstance(context).sendBroadcast(in);
The great thing about this approach is that you can simply receive the result on the Main thread without having to do anything extra. The down side is that the method is a lot slower than using a callback.
In order to use a callback, you can explicitly get a Handler on the main thread:
Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() {    @Override      public void run() {        MainActivity.this.onResult();    } // This is your code }; mainHandler.post(myRunnable);
Or, if you are creating the Handler on the main thread, simply calling new Handler() should return a Handler on the main thread.
Implementation of HandlerThreads by creating a custom HandlerThread, is simply a combination of the techniques that I have shown above. There is a great blog post by Nikita that explains how to do this. He also has a great post in which he explain Looper, Handler and HandlerThread and the interaction between them I highly recommend reading this to get a deeper understanding of how Android apps work.
0 notes
jacob-cs · 7 years ago
Video
youtube
android looper , handler, handlerthread
기본개념 정리와 실제 예제
my review point is 9 / 10
https://youtu.be/Yo3VT-fZr68     thread, handler, looper를 이용한 코드예시
https://youtu.be/dSb-K024A6U
https://youtu.be/E81yFwQ0NpI
https://youtu.be/b80LbWVERL4
https://youtu.be/998tPb10DFM
0 notes