user1549123
user1549123

Reputation: 25

Progress Dialog and Threading

I am targeting Android 4.0 and am communicating with a telemetry device using TCP/IP. Android 4.0 forces all networking to be done in a separate thread. First I open a socket, then I contact the device and download some information all from a separate thread. At this point I want to display a progress dialong to show the progress of downloading more detailed information. My problem is that I cannot show the progress dialog from anywhere but the main UI. But, I do not know when I have reached the point in the other thread where I am ready to display the progress dialog. Is there some way I can check for this from the main UI without tying up the system?

Upvotes: 0

Views: 165

Answers (3)

Sogger
Sogger

Reputation: 16132

To trigger the dialog on your main ui, you need to use 'context.runOnUiThread()' where context is the reference to your display activity. It's also worth looking into using an AsyncTask.

Here is an android blog post that explains everything in detail: http://android-developers.blogspot.ca/2009/05/painless-threading.html

As an aside, you can also just start displaying a indeterminate progress dialog from the start, so the user is never waiting without visual feedback, then switch to the determinate when you know the download details.

Upvotes: 0

Anirudh
Anirudh

Reputation: 2524

AsyncTask is framework provided utility that is meant for cases like you describe. From the other thread, i.e the one in which the async task is executing, you can publish progress using publishProgress() method of AsyncTask. Its asynchronous and runs on a different thread but has event callbacks that run on main thread. OnProgressUpdate() is the method where you can work with a progress dialog.

http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 1

Alix Bloom
Alix Bloom

Reputation: 217

Use Handler, like that :

final int PROGRESS_BY = 1;

    final Handler handler = new Handler()
    {
        public void handleMessage(android.os.Message msg) 
        {
            switch (msg.what)
            {
                case PROGRESS_BY :
                    progressBar.setProgress((Integer) msg.obj);
                    break;
            }
        }
    };

    Thread thread = new Thread()
    {
        @Override
        public void run() 
        {
            super.run();
            // do something
            Message msg = new Message();
            msg.what = PROGRESS_BY;
            msg.obj = new Integer(10);
            handler.sendMessage(msg);
            // do something
            [...]
        }
    };

Upvotes: 1

Related Questions