11

I have a service which receives a command from the Internet and launches a background thread. This thread is passed a handler from the service (the service is bounded and passed the handler) and sends a message to the handler to take a picture. I'm stuck on the implementation of the handler.

static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            //TODO: Handle different types of messages
            mCamera.takePicture(null, null, MainActivity.this);
        }
};

Questions:

  • Does Handler need to be static? Without static, I get "This Handler class should be static or leaks might occur"
  • Does mCamera need to be static? I've been told to make mCamera static, but why is this necessary? Is there a way to setup takePicture without making mCamera static?
  • What's the proper way to pass the reference to MainActivity? Right now I get the error: "No enclosing instance of the type MainActivity is accessible in scope"
Rich
  • 785
  • 1
  • 9
  • 22

4 Answers4

12

You can make a class (Activity/Service) implement Handler.Callback and create a new Handler for it via new Handler(this).

S.D.
  • 29,290
  • 3
  • 79
  • 130
  • This did the trick as it simplifies a lot of the overhead (I don't have to pass the object, etc) compared to the other methods described in this post. – Rich Jun 17 '13 at 13:35
1

You can change your code as follows:

    static Handler handler = new Handler() {

            MainActivity mActivity;

            @Override
            public void handleMessage(Message msg) {
                //TODO: Handle different types of messages
                if(mActivity != null) {
                    mActivity.mCamera.takePicture(null, null, mActivity);
                }
            }
    };

    void MainActivity::onCreate(Bundle savedState) {
         ...
         handler.mActivity = this;
    }

    void MainActivity::onDestroy() {
        ...
        handler.mActivity = null;
    }     
Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
0

Here is a good explanation why handler should be static:

This Handler class should be static or leaks might occur: IncomingHandler

About your other question, if you make Handler static you should also make all the fields that you use inside it static.

Community
  • 1
  • 1
Marek
  • 3,935
  • 10
  • 46
  • 70
0

You can use Message member obj and pass the desired object to the handler.

static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            //TODO: Handle different types of messages
            //TODO: handle cast exception
            final MainActivity activity = (MainActivity) msg.obj;
            final Camera camera = activity.getCamera();
            camera.takePicture(null, null, activity);
        }
};
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134