Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass progress value from thread to activity?

I am having a design issue sending progress bar value from class called from a Thread in Activity class to update the GUI, as the following

[The code snippet don't compile it's for explaining only]:

Class A : Extend Activity {
  new Thread(new Runnable() 
    {
       public void run() 
       {
            B objB = new B();
            objB.DownloadFile();
        }
    }).start();
}

Class B {
    public void DownloadFile()
    {
       ... some work [preparing SOAP request]
       while(response.read())
       {
         //send calculated progress to Class A to update the progress value
       }

    }

}

Any help or guide would be greatly appreciated

like image 663
Ahmad Kayyali Avatar asked Feb 08 '11 08:02

Ahmad Kayyali


1 Answers

I've used a Handler to achieve this effect. Create it in the Activity that you create the ProgressDialog in, then pass the Handler into the maethod you want to get the progress from. Then you can send a message back to the calling Activity to update the progress:

public class ClassA extends Activity {
    ...
    private static final int HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE = 0;
    ...
    new Thread(new Runnable() 
    {
        public void run() 
        {
            B objB = new objB();
            objB.DownloadFile(handler);
        }
    }).start();
    ...
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case Constants.HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE:
                progress.setProgress(msg.arg1);
                break;
            default:
                Log.w("TAG_NAME","handleMessage / Message type not recognised / msg.what = "+String.valueOf(msg.what));
            }
        }
    };
}

Class B 
{
    public void DownloadFile(Handler handler)
    {
       ... some work [preparing SOAP request]
       while(response.read())
       {
         //send calculated progress to Class A to update the progress value
           sendMessage(handler,HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE,progress);
       }
    }
    private void sendMessage(Handler handler,int what, int arg1){
        Message msg = Message.obtain();
        msg.what = what;
        msg.arg1 = arg1;
        handler.sendMessage(msg);
    }
}
like image 98
dave.c Avatar answered Sep 18 '22 02:09

dave.c