I want to build an simple android download app without using download manager. I try to implement it with asynctask. But I don't know how to implement "pausing and resuming when Based on the internet condition". That is when I click the start button, it start to download if connected. If internet is unconnected, it pause, and then the internet is connected, it resume automatically. I know it can be finished by using download manager easily, but how can I implement it without that? I'm a totally beginner, hope someone can give me an simple example of that.
Yimeng -2 Newbie Poster
Edited by peter_budo because: Moved to Mobile Development section
Dani AI
Generated
— AsyncTask isn't a good fit for a download that must pause automatically on network loss and resume later. AsyncTasks are tied to Activity lifecycles and can be killed; use a dedicated Service (foreground on modern Android) with a worker thread, detect connectivity separately, and implement HTTP range requests so you can resume where you left off.
Basic approach (high level)
- Run the download in a Service so it survives UI changes and system limits.
- Write bytes incrementally to disk (use RandomAccessFile) and keep a persisted record (or simply use the file length) as the resume offset.
- When (re)connecting, send a Range header like
Range: bytes=<offset>-. Servers that support resume reply 206 (Partial Content). - Pause by setting a
pausedflag; the worker thread should wait on a lock while paused. Resume by clearing the flag and notifying the lock. - Monitor network with ConnectivityManager (registerNetworkCallback on API21+, or a BroadcastReceiver for older devices) and call pause()/resume() automatically.
Minimal, illustrative worker loop (simplified)
// in a Service worker thread (simplified)
volatile boolean paused = false;
final Object pauseLock = new Object();
public void run() throws Exception {
long downloaded = destFile.length();
while (!stopped) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Range", "bytes=" + downloaded + "-");
conn.setConnectTimeout(15000);
conn.setReadTimeout(30000);
conn.connect();
int code = conn.getResponseCode();
if (code == 206 || (code == 200 && downloaded == 0)) {
try (InputStream in = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(destFile, "rw")) {
raf.seek(downloaded);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
synchronized (pauseLock) { while (paused) pauseLock.wait(); }
raf.write(buf, 0, len);
downloaded += len;
// send progress updates (LocalBroadcast / callback)
}
break;
}
} else {
throw new IOException("Unexpected response: " + code);
}
}
}
public void pause() { paused = true; }
public void resume() { synchronized (pauseLock) { paused = false; pauseLock.notifyAll(); } } Troubleshooting and cautions
- Check server support: look for
Accept-Rangesand expect HTTP 206. If server returns 200 for a resumed request, you must restart or handle duplication. - Use foreground Service on Android O+ and handle battery-optimization issues.
- If the connection drops mid-read you may get IOExceptions — catch them, set paused, and wait for connectivity to return, then reconnect using the saved offset.
- Libraries like OkHttp simplify retries and cancellation; Android's DownloadManager handles pause/resume for you if you decide not to implement everything yourself.
's linked post points in the right direction; the code sketch above gives a concrete way to combine connection callbacks, a pause flag, and HTTP Range to achieve automatic pause/resume.
peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster
Have look at this blog http://mobiarch.wordpress.com/2012/07/20/pausing-and-resuming-background-work-in-android/
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.