Search code examples
androidserviceandroid-download-manager

Android background download on WiFi only


My app requires to download files in the evening if there is Wi-Fi. Is Service 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?


Solution

  • 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/somefile.asd");
    
    DownloadManager.Request request = new DownloadManager.Request(uri);
    // allowing Wi-Fi only
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    
    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() {
        @Override
        public void onReceive(Context context, Intent intent) {
    
            // the ID of the finished download
            long downloadedId = intent.getLongExtra(
                DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    
            // do whatever you'd like here
        }
    };
    

    And register/unregister it:

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(downloadReceiver,
            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    
    @Override
    protected void onPause() {
        unregisterReceiver(downloadReceiver);
        super.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" />