0

My user clicks a button. 500 milliseconds after the button get's pressed I want to start the next action. After the button is pressed my app usually does 50-100 milliseconds of additional processsing.

Therefore I start a a new thread right after the button get's pressed via my class:

private class WaitForUpdating extends Thread {
    /** The app waits for duration of the passed time (in ms)
    and afterwards loads the next card.
     */
    public WaitForUpdating(int time) {
        this.start();
    }

    public void run() {
        try {
            Thread.sleep(500);

            Message msg = new Message();
            Bundle b = new Bundle();
            b.putInt("State", UPDATING);
            msg.setData(b);
            mHandler.sendMessage(msg);
        } catch (InterruptedException e) {
        }
    }
}

Then I try to handle the result via:

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Bundle b = msg.getData();
        int state = b.getInt("State");
        if (state == ScoreAndTimeFragment.UPDATING) {
            try {
                setCard();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
};

The Android linter shows me that this produces a Handler leak. What can I do to not have the leak in this case?

Christian
  • 25,249
  • 40
  • 134
  • 225
  • `Handler` being an anonymous inner class has a reference to your `Activity` which will be leaking when, say, the phone is rotated because of this line in the `run()` method: `mHandler.sendMessage(msg)`. The point is that the leak won't last more than 500 milliseconds (+ a bit more). It is not a long living leak, so you might ignore it. If you don't want to, make `Handler` to be a private static class and use `WeakReference` to the `Activity` within it. – Onik Jan 26 '17 at 01:44
  • [This answer](http://stackoverflow.com/questions/39562914/is-it-possible-for-a-callback-method-to-be-called-after-ondestroy/39563751#39563751) has more explanation regarding the leak and a link with the approach described. Also have a look at the comment by David Wasser below the answer regarding the problem the kind of leak may lead to. – Onik Jan 26 '17 at 01:47

0 Answers0