In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to solve memory leakage caused by using Handler in Android". Xiaobian shows you the operation process through actual cases. The operation method is simple and fast, and the practicality is strong. I hope this article "how to solve memory leakage caused by using Handler in Android" can help you solve the problem.
1. What is a memory leak?
Java uses a directed graph mechanism to automatically check objects in memory through GC (when to check is determined by the virtual machine), and if GC finds an object or group of objects in an unreachable state, it will reclaim the object from memory. That is, an object that is not pointed to by any reference will be reclaimed when it is discovered by GC, and if a set of objects contains only references to each other and no references from outside them (for example, two objects A and B hold references to each other, but no external objects hold references to A or B), this is still unreachable and will also be reclaimed by GC.
Android uses Handler to cause memory leaks
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); }};
When we often use handler, it will be defined as above, but the lint detection of AS will automatically report an error warning prompt, as shown below
The above is a simple Handler usage. When using inner classes (including anonymous classes) to create a Handler, the Handler object implicitly holds a reference to an outer class object (usually an Activity)(how else can you manipulate a View in an Activity through a Handler?). The Handler is usually accompanied by a time-consuming background thread (e.g. pulling images from the network) that notifies the Handler via a message mechanism after the task is completed (e.g. the image is downloaded) and then updates the image to the interface. However, if the user closes the Activity in the middle of a network request, normally, the Activity is no longer in use, and it may be recycled during GC checking, but since the thread has not finished executing at this time, and the thread holds a reference to the Handler (otherwise how can it send a message to the Handler?), This Handler also holds a reference to the Activity, which causes the Activity to not be recycled (i.e., memory leak) until the end of the network request (e.g., the image is downloaded). In addition, if you execute the Handler's postDelayed() method, which loads your Handler into a Message and pushes that Message into a MessageQueue, then before the delay you set arrives, there will be a chain of MessageQueue -> Message -> Handler -> Activity, causing your Activity to be held by references and cannot be recycled.
Second, the harm of memory leakage
Memory leak hazard is that the virtual machine will occupy too much memory, resulting in OOM (memory overflow), program errors.
For Android apps, it's when your user opens an Activity, closes it after use, leaks memory; opens it again, closes it again, leaks again; and after a few times, the program consumes more memory than the system limit, FC.
III. Solutions
Solution to memory leak caused by Handler
Method 1 (Official Solution):
private Handler mHandler2 = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { //do something return false; } });
Method 2: Protect through program logic.
1. Stop your background thread when closing an Activity. When a thread is stopped, it is equivalent to cutting the line between Handler and external connection, and the Activity will naturally be recycled at the appropriate time.
2. If your Handler is referenced by a delay Message, then use the removeCallbacks() method of the corresponding Handler to remove the message object from the message queue.
Method 3: Declare Handler as a static class.
PS: In Java, both non-static inner classes and anonymous inner classes implicitly hold references to their outer classes, and static inner classes do not hold references to outer classes.
Static classes don't hold objects from external classes, so your Activity can be recycled at will. Because the Handler no longer holds references to external class objects, the program does not allow you to manipulate objects in Activities in the Handler. So you need to add a WeakReference to the Activity in the Handler.
The code is as follows:
static class MyHandler extends Handler { WeakReference mWeakReference; public MyHandler(Activity activity) { mWeakReference = new WeakReference(activity); } @Override public void handleMessage(Message msg) { final Activity activity = mWeakReference.get(); if (activity != null) { if (msg.what == 1) { activity.noteBookAdapter.notifyDataSetChanged(); } } } }
Either way, remember to remove messages from the handler queue after the end of the current interface declaration cycle
handler.removeCallbacksAndMessages(null);
PS: What is WeakReference?
WeakReference weak reference, as opposed to strong reference (that is, we often say reference), its characteristic is that GC will ignore weak reference when recycling, that is, even if there is a weak reference to an object, but as long as the object is not pointed to by strong reference (in fact, most of the time there is no soft reference, but the concept of soft reference can be ignored here), the object will be collected when GC checks. For the above code, after the user closes the Activity, even if the background thread has not ended, because there is only one weak reference from the Handler pointing to the Activity, GC will still collect the Activity at the time of inspection. In this way, the memory leak problem will not occur.
About "how to solve the memory leak caused by using Handler in Android" is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the industry information channel. Xiaobian will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.