0

In my application, I use AsyncTask to download large files (300M+). I noticed that when the user turns off their screen (locks their device), the wifi will disconnect and the download will hang.

I wonder if it is possible to avoid this?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
hguser
  • 35,079
  • 54
  • 159
  • 293
  • Do not keep screen on. Firt take a look on DownloadManager class ... if you still wana use asynctask search for wake locks(PowerManager class) – Selvin Jan 06 '14 at 08:05
  • DownloadManager is only supported at api level with 9+. I can not use it. – hguser Jan 06 '14 at 08:06
  • There is also http://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html – Selvin Jan 06 '14 at 08:18

2 Answers2

1

You required to implement WakeLock in your application. Wakelock will wake up the CPU incase of screen is off and performs the operations in normal ways.

Write down following code before starting the AsyncTask,

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb");
wl.acquire();

You need to write wl.release(); on PostExecution() method. And you need to define permission in AndroidManifest.xml as follows,

<uses-permission android:name="android.permission.WAKE_LOCK" />
Vigbyor
  • 2,568
  • 4
  • 21
  • 35
  • And don't forget to release it when your done by doing wl.release(). I encourage you to read this (http://developer.android.com/reference/android/os/PowerManager.WakeLock.html ) because wwakelock can hardly affect battery consumption. – tanou Jan 06 '14 at 08:13
  • @tanou, please read the full answer, I already mentioned that part. :) – Vigbyor Jan 06 '14 at 08:14
  • my bad, page wasn't refreshed ;) – tanou Jan 06 '14 at 08:21
  • Wonderful, this solve my problem? Can you explain why? – hguser Jan 06 '14 at 10:39
0

The common practice in this case is to take a WakeLock to keep the CPU awake, and take a WifiLock to keep the wifi connected, so that your app keeps running even if the screen is turned off.

Don't forget to release the locks when you're done!

PaF
  • 3,297
  • 1
  • 14
  • 15