ywj7931 ywj7931 - 10 months ago 56
Android Question

Android background download on WiFi only

My app requires to download files in the evening if there is Wi-Fi. Is

the best way to implement it?

If user closes my app, does that mean I cannot download in any way? That means my user has to keep my app in the background?


You could just use DownloadManager and restrict the allowed network types to Wi-Fi only.

For example:

DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse("http://something.xyz");

DownloadManager.Request request = new DownloadManager.Request(uri);
// allowing Wi-Fi only

long id = manager.enqueue(request);

To get notified when your download completes, you could define a receiver for the ACTION_DOWNLOAD_COMPLETE broadcast:

private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        long downloadedId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        // do whatever you'd like here

And register/unregister it when appropriate:

protected void onResume() {
        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

protected void onPause() {

Don't forget to add the appropriate permissions to your Manifest:

<!-- required -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- optional -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />