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"
4

4 回答 4

12

您可以通过实现一个类(活动/服务)Handler.Callback并为其创建一个新的处理程序new Handler(this)

于 2013-06-17T04:51:03.283 回答
1

您可以按如下方式更改代码:

    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;
    }     
于 2013-06-17T04:37:25.190 回答
0

这是一个很好的解释为什么处理程序应该是静态的:

这个 Handler 类应该是静态的,否则可能会发生泄漏:IncomingHandler

关于您的另一个问题,如果您将 Handler 设为静态,您还应该将您在其中使用的所有字段设为静态。

于 2013-06-17T04:32:45.050 回答
0

您可以使用Message成员obj并将所需的对象传递给处理程序。

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);
        }
};
于 2013-06-17T04:34:01.317 回答