Memory safer implementation of android.os.Handler

Overview

Android Weak Handler

Memory safer implementation of android.os.Handler

Problem

Original implementation of Handler always keeps hard reference to handler in queue of execution. Any object in Message or Runnable posted to android.os.Handler will be hard referenced for some time. If you create anonymous Runnable and call to postDelayed with large timeout, that Runnable will be held in memory until timeout passes. Even if your Runnable seems small, it indirectly references owner class, which is usually something as big as Activity or Fragment.

You can read more on our blog post.

Solution

WeakHandler is trickier than android.os.Handler , it will keep WeakReferences to runnables and messages, and GC could collect them once WeakHandler instance is not referenced any more.

Screenshot

Usage

Add JitPack repository to your build.gradle:

repositories {
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'com.github.badoo:android-weak-handler:1.2'
}

Use WeakHandler as you normally would use Handler

import com.badoo.mobile.util.WeakHandler;

public class ExampleActivity extends Activity {

    private WeakHandler handler; // We still need at least one hard reference to WeakHandler

    protected void onCreate(Bundle savedInstanceState) {
        handler = new WeakHandler();
        ...
    }

    private void onClick(View view) {
        handler.postDelayed(new Runnable() {
            view.setVisibility(View.INVISIBLE);
        }, 5000);
    }
}

Credits

Weak Handler is brought to you by Badoo Trading Limited and it is released under the MIT License.

Created by Dmytro Voronkevych

##Blog Read more on our tech blog or explore our other open source projects

Comments
  • support handleMessage ???

    support handleMessage ???

    Hi.it support handleMessage or not like this?

        Handler handlerButtonToggleAction = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        MediaArticle article = (MediaArticle) msg.obj;
                        if (article.isCached()) {
                            showArticleActionDialog(article);
                        } else {
                            toggleArticleCacheStatus(article);
                        }
                        break;
                }
            }
        };
    

    In my project. i have a main handler in activity to update ui by message tag. Thanks.

    opened by liufsd 9
  • Postdelay a runnable but does not run after activity recycled by GC

    Postdelay a runnable but does not run after activity recycled by GC

    Some code in activity like this:

    new WeakHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // do something
                }
            }, 10_000);
    ``
    If the activity finished within 10 seconds, the runnable will not run.Is there any idea to run the runnable after activity destroyed?
    P.S.
    I found some reason in WeakHandler.java
    
    final ChainedRef mRunnables = new ChainedRef(mLock, null);
    //`mRunnables` recycled after activity destroyed so nothing keep reference to the following runnable
    
    opened by mricefox 2
  • WeakHandler should not be used without hard reference from outside.

    WeakHandler should not be used without hard reference from outside.

    WeakHandler should not be used without hard reference from outside. this is from https://techblog.badoo.com/blog/2014/08/28/android-handler-memory-leaks/ Why is that? This is what is meant? Please give an example to explain this.

    opened by androidmalin 1
  • callback sometimes occurs null pointer

    callback sometimes occurs null pointer

    Just as #11 say: callback sometimes occurs null pointer

    I have an idea: Check if tag of callback and tag of message-bundle are same by setting a tag when send message.

    It can guarantee a one-to-one correspondence between callbacks and messages.

    opened by Rocksnake 0
  • optimize when msg.getCallback() not null

    optimize when msg.getCallback() not null

    leak could still occur when used like bellow: WeakHandler handler = new WeakHandler(); Message m = Message.obtain(handler.getExecHandler(), new Runnable() { @Override public void run() { //do something } }); handler.sendMessageDelayed(m, delaytimes);

    although postDelay() should be used here, but what if when we get message like this: Message message = Message.obtain(m); and m has a callback?

    so maybe sendMessageXX() methods should be optimized:

    public final boolean sendMessage(Message msg) {
        if (msg.getCallback() != null) {
            return mExec.post(msg.getCallback());
        }
        return mExec.sendMessage(msg);
    }
    
    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        if (msg.getCallback() != null) {
            return postAtFrontOfQueue(msg.getCallback());
        }
        return mExec.sendMessageAtFrontOfQueue(msg);
    }
    
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        if (msg.getCallback() != null) {
            return postDelayed(msg.getCallback(), uptimeMillis);
        }
        return mExec.sendMessageAtTime(msg, uptimeMillis);
    }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis) {
        if (msg.getCallback() != null) {
            return postDelayed(msg.getCallback(), delayMillis);
        }
        return mExec.sendMessageDelayed(msg, delayMillis);
    }
    
    opened by wangyong0716 0
Releases(1.3)
Owner
Badoo Tech
Badoo Tech
vShell (Virtual Shell) — a successor of Termux project which provides an alternate implementation of the Linux terminal emulator for Android OS

vShell (Virtual Shell) — a successor of Termux project which provides an alternate implementation of the Linux terminal emulator for Android OS

null 2 Feb 1, 2022
Starter-Android-Library - Starter Android Library is an Android Project with Modular Architecture.

Starter-Android-Library - Starter Android Library is an Android Project with Modular Architecture.

OpenBytes 1 Feb 18, 2022
SL4A brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device.

#Scripting Layer for Android (SL4A) SL4A brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreter

Damon Kohler 2.3k Dec 23, 2022
****. Use the native and support library variants instead - https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html. An android library that makes it easy to add custom fonts to edittexts and textviews

Add to your project Add this line to your dependencies in build.gradle compile 'in.workarounds.typography:typography:0.0.8' Using the views There are

Workarounds 43 Nov 6, 2021
ZXing ("Zebra Crossing") barcode scanning library for Java, Android

Project in Maintenance Mode Only The project is in maintenance mode, meaning, changes are driven by contributed patches. Only bug fixes and minor enha

ZXing Project 30.5k Dec 27, 2022
RxJava binding APIs for Android's UI widgets.

RxBinding RxJava binding APIs for Android UI widgets from the platform and support libraries. Download Platform bindings: implementation 'com.jakewhar

Jake Wharton 9.7k Jan 6, 2023
A gradle plugin for getting java lambda support in java 6, 7 and android

Gradle Retrolambda Plugin This plugin will automatically build your java or android project with retrolambda, giving you lambda goodness on java 6 or

Evan Tatarka 5.3k Jan 5, 2023
A comprehensive tutorial for Android Data Binding

精通 Android Data Binding 更多干货可移步至个人主页 QQ 交流群:324112728 ,或者点击链接加入QQ群 官方虽然已经给出了教程 - Data Binding Guide (中文版 - Data Binding(数据绑定)用户指南) ,但是实践之后发现槽点实在太多,于是就

Fei Liang 2.6k Dec 6, 2022
A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

Development in this repository is stopped. Future development continues on https://github.com/yigit/android-priority-jobqueue ========================

Path Mobile Inc Pte. Ltd. 2.4k Dec 9, 2022
An android library for displaying fps from the choreographer and percentage of time with two or more frames dropped

DEPRECATED TinyDancer is deprecated. No more development will be taking place. Check out the Google Android developer documentation for UI performance

Friendly Robot 1.9k Jan 3, 2023
Android Library to help you with your runtime Permissions.

PermissionHelper Android Library to help you with your runtime Permissions. Demo Android M Watch it in action. Pre M Watch it in action. Nexus 6 (M) N

Kosh Sergani 1.2k Dec 14, 2022
Android validation library which helps developer boil down the tedious work to three easy steps.

AwesomeValidation Introduction Implement validation for Android within only 3 steps. Developers should focus on their awesome code, and let the librar

Jing Li 1.1k Dec 17, 2022
📄The reliable, generic, fast and flexible logging framework for Android

logback-android v2.0.0 Overview logback-android brings the power of logback to Android. This library provides a highly configurable logging framework

Tony Trinh 1.1k Jan 8, 2023
Android framework for node.js applications

Introduction Anode is an embryonic framework for running node.js applications on Android. There are two main parts to this: a port of node.js to the A

Paddy Byers 586 Dec 9, 2022
It makes a preview from an url, grabbing all the information such as title, relevant texts and images. This a version for Android of my web link preview https://github.com/LeonardoCardoso/Link-Preview

LeoCardz Link Preview for Android It makes a preview from an url, grabbing all the information such as title, relevant texts and images. Visual Exampl

Leonardo Cardoso 420 Nov 19, 2022
AndroidPermissions 4.2 0.0 Java Android M was added to check Permission. but Permission check processing is so dirty.

Android Permissions Checker Android M was added to check Permission. but Permission check processing is so dirty. This Project is to be simple, Checki

Steve SeongUg Jung 340 Nov 11, 2022
A plug and play ;) android library for displaying a "rate this app" dialog

Easy Rating Dialog This lib provides a simple way to display an alert dialog for rating app. Default conditions to show: User opened the app more than

Fernando Martínez 111 Dec 30, 2022
Tool for Android app development

RateMeMaybe Asks the user if (s)he wants to open the Play Store to rate your application when certain requirements are met (see below). This can and s

Nicolai Spohrer 98 Dec 30, 2022
AudioPlayerView is an Android view that loads audio from an url and have basic playback tools.

AudioPlayerView AudioPlayerView is an Android view that loads audio from an url and have basic playback tools. It makes use of the Android MediaPlayer

Hugo Matilla 86 Nov 29, 2022