Android: how to use Handler handleMessage and access a link to MainActivity

I have a service that receives a command from the Internet and starts a background thread. This stream is passed by the handler from the service (the service is limited and passed by the handler) and sends a message to the handler to take a snapshot. I am stuck with a handler implementation.

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

Questions:

  • Should the handler be static? Without static, I get: "This handler class must be static or there may be a leak"
  • Does mCamera need to be static? I was told to make mCamera static, but why is this necessary? Is there a way to configure takePicture without making mCamera static?
  • What is the correct way to pass a link to MainActivity? Right now I get the error: "No closing instance of type MainActivity is available in scope"
+7
source share
4 answers

You can create an implementation of the Handler.Callback class (Activity / Service) and create a new handler for it via new Handler(this) .

+9
source

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; } 
+2
source

Here is a good explanation why the handler should be static:

This handler class must be static or leaks may occur: IncomingHandler

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

0
source

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); } }; 
0
source

All Articles