Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7429539
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T08:59:08+00:00 2026-05-29T08:59:08+00:00

I need to download thousands of objects. I need to be able to pause

  • 0

I need to download thousands of objects. I need to be able to pause and resume downloads and to display the progress. I’m not good in multithreading, so I’ve compiled my code from different sources (I’ve simplified maths and UI but left logic intact):

public class DownloadActivity extends Activity {
    private static final int MSG_FINISH = 1;
    private static final int MSG_PROGRESS = 2;

    private long total;
    private ProgressBar progress;

    private static DownloadThread thread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download);

        progress = (ProgressBar) findViewById(R.id.progress);

        total = 10000;
        progress.setMax((int) total);

        if (thread == null)
            thread = new DownloadThread(progressHandler, 15000, 25000);
        else
            thread.setHandler(progressHandler);

        ((Button) findViewById(R.id.start_button)).setEnabled(thread.paused());
        ((Button) findViewById(R.id.pause_button)).setEnabled(! thread.paused());

        ((Button) findViewById(R.id.start_button)).setOnClickListener(startOnClickListener);
        ((Button) findViewById(R.id.pause_button)).setOnClickListener(pauseOnClickListener);
    }

    @Override
    public void onBackPressed()
    {
        thread.pause();
        thread = null;
        super.onBackPressed();
    }

    private OnClickListener startOnClickListener = new OnClickListener() {
        public void onClick(View v) {
            ((Button) findViewById(R.id.start_button)).setEnabled(false);
            thread.unpause();
            ((Button) findViewById(R.id.pause_button)).setEnabled(true);
        }
    };

    private OnClickListener pauseOnClickListener = new OnClickListener() {
        public void onClick(View v) {
            ((Button) findViewById(R.id.pause_button)).setEnabled(false);
            thread.pause();
            ((Button) findViewById(R.id.start_button)).setEnabled(true);
        }
    };

    final Handler progressHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MSG_PROGRESS:
                    if (progress != null)
                    {
                        long current = msg.getData().getLong("current");
                        progress.setProgress((int) current);
                    }
                    break;
                case MSG_FINISH:
                    Button pause = ((Button) findViewById(R.id.pause_button));
                    if (pause != null)
                        pause.setEnabled(false);
                    break;
            }
        }
    };

    private class DownloadThread extends Thread
    {
        Handler handler;
        long current;
        long x;
        long x2;
        LinkedList<Long> pendingList;
        Thread threadA;
        Thread threadB;
        Thread threadC;
        Thread threadD;

        boolean paused = true;

        DownloadThread(Handler h, long x1, long x2)
        {
            current = 0;
            this.x = x1;
            this.x2 = x2;

            pendingList = new LinkedList<Long>();
            handler = h;
            threadA = new Thread(this);
            threadA.start();
            threadB = new Thread(this);
            threadB.start();
            threadC = new Thread(this);
            threadC.start();
            threadD = new Thread(this);
            threadD.start();
        }

        public void run()
        {
            while (! isInterrupted())
            {
                synchronized (this)
                {
                    if (paused)
                    {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                }
                Long l;
                synchronized (pendingList)
                {
                    if (pendingList.size() == 0)
                    {
                        x++;
                        if (x > x2)
                        {
                            continue;
                        }
                        l = new Long(x);
                        pendingList.add(l);
                        synchronized (this)
                        {
                            notifyAll();
                        }
                        continue;
                    }
                    else
                    {
                        l = pendingList.poll();
                        if (l == null)
                        {
                            synchronized (this)
                            {
                                try {
                                    wait();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            continue;
                        }
                    }
                }
                Object d = DownloadFactory.download(l);
                if (d != null)
                {
                    synchronized (DownloadActivity.this)
                    {
                        current++;
                        sendProgress();
                    }
                }
                else
                {
                    synchronized (pendingList)
                    {
                        pendingList.add(l);
                    }                   
                }
            }
        }

        public void interrupt()
        {
            threadA.interrupt();
            threadB.interrupt();
            threadC.interrupt();
            threadD.interrupt();
        }

        public synchronized boolean paused()
        {
            return paused;
        }

        public synchronized void pause()
        {
            paused = true;
        }

        public synchronized void unpause()
        {
            sendProgress();
            paused = false;
            notifyAll();
        }

        public synchronized void setHandler(Handler h)
        {
            handler = h;
            sendProgress();
        }

        private void sendProgress()
        {
            Message msg = handler.obtainMessage(MSG_PROGRESS);
            Bundle b = new Bundle();
            b.putLong("current", current);
            msg.setData(b);
            handler.sendMessage(msg);
            if (current == total)
                handler.sendEmptyMessage(MSG_FINISH);
        }
    }
}

This code works fine and does everything I want but I understand that it is ugly and not correct (at least in putting nesting threads). So what is the nice and androidish way to accomplish the same task?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T08:59:09+00:00Added an answer on May 29, 2026 at 8:59 am

    Ok I am not a concurrency professional but using a Thread which contains 4 other threads, too, sounds pretty evil 🙂

    If you just want to make a download manager this is way beyond necessary work. If you use API 9 or above, check the DownloadManager.

    Otherwise I recommend to use a simple Manager class that contains a queue and handles the add/remove and start/restart/stop of the downloads. If the queue has an element, I would start a AsyncTask which downloads the element and removes it from the queue if successfully downloaded. If not it tries to resume.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to download a file using Java. I can use this code to
I need to download a text file using php code. The file is having
i need to download large pdf from web and i created a progress bar
I need to download an xml file using PHP. I am able to read
I need to download the source code of a project that is on code.google.com
I need to download 6 images from server and display on a table in
I need to download several files via http in Python. The most obvious way
I need to download a large file (2 GB) over HTTP in a C# console
I need to download jasper reports professional trail version, can anyone help?
I need to download file from FTP server and make some changes on it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.