0

Please have a look at the code below: When I use handler like this I get a warning(This Handler class should be static or leaks might occur ) Can someone tell me what is the best way to do this?

private void cacheImages() {

            try {

                    // The handler is inside the function because
                    // normally this function is called once.
                    final Handler cacheHandler = new Handler() {

                    public void handleMessage(Message message) {

                        switch (message.what) {

                        case ThreadState.STARTED:
                            cachingDialog.setMax(message.arg1);
                            break;

                        case ThreadState.PROGRESSION_UPDATE:
                            cachingDialog.setProgress(message.arg1);
                            break;
Ahmad
  • 69,608
  • 17
  • 111
  • 137

1 Answers1

0

I do believe you've answered your own question.

You've put a final on a cached handler with a new keyword inside a function.

This is the compiler warning you NOT do do that. cacheImages() can be called more than once, so don't do this!

Can you just declare the handler OUTSIDE of the cacheImages() function in the main activity scope?

EDIT: Example

            final Handler cacheHandler = new Handler() {

                public void handleMessage(Message message) {

                    switch (message.what) {

                    case ThreadState.STARTED:
                        cachingDialog.setMax(message.arg1);
                        break;

                    case ThreadState.PROGRESSION_UPDATE:
                        cachingDialog.setProgress(message.arg1);
                        break;
                    }
                }

private void cacheImages() {

        try {
           ... do stuff
        }
        catch (Exception e) {
           ... do stuff
        }
John Kroetch
  • 1,143
  • 8
  • 15