javaandroidmultithreadinghandlers

Android: runnables in different class files


I am creating an android app and I am connecting and exchanging data with a remote server. Up to now, I have been using threads and handlers withing my activity class to interface with the server, but the code is getting increasingly messy and long. I believe that having more classes would make it (the code) easier to manage.

This is probably a large gap in my programming knowledge, but I can't figure out how to put runnables in different classes and then have them return messages to the main activity.

Thankyou in advance, sample code is preferred in answers.


Solution

  • You can pass a handler from the activity to the second class, and pass a message through it when needed.

    public class MyActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstance) {
            // ....
            Handler myHandler = new Handler() {
                @Override
                public void handleMessage (Message msg) {
                    doCoolStuffWhenMessageReceived();
                }
            }
            MySecondClass secondClass = new MySecondClass(myHandler);
            // ....
        }
    }
    

    public class MySecondClass {
        private Handler handler;
        public MySecondClass(Handler handler){
            this.handler = handler;
        }
    
        private void someMethodToCallActivity() {
            handler.sendEmptyMessage(0);
        }
    
    }