android downloading multiple files with InputStream FileOutputStream

╄→гoц情女王★ 提交于 2019-12-24 01:45:11

问题


So I have an app which downloads certain files, dedicated to a client of mine who is hosting his files on a remote location, and i'm doing so using the code below:

public class DownloadService extends IntentService {

    private int result = Activity.RESULT_CANCELED;
    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        String urlPath = intent.getStringExtra(URL);
        String fileName = intent.getStringExtra(FILENAME);
        File output = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                fileName);
        if (output.exists()) {
            output.delete();
        }

        URLConnection streamConnection = null;
        InputStream stream = null;
        FileOutputStream fos = null;
        try {

            URL url = new URL(urlPath);
            streamConnection = url.openConnection();
            stream = streamConnection.getInputStream();
            streamConnection.connect();
            long lengthofFile = streamConnection.getContentLength();
            InputStream reader = stream;
            bis = new BufferedInputStream(reader);
            fos = new FileOutputStream(output.getPath());
            int next = -1;
            int progress = 0;
            int bytesRead = 0;
            byte buffer[] = new byte[1024];
            while ((bytesRead = bis.read(buffer)) > 0) {
                fos.write(buffer, 0, bytesRead);
                progress += bytesRead;
                int progressUpdate = (int)((progress * 100) / lengthofFile);
                Intent testIntent = new Intent(".MESSAGE_INTENT");
                testIntent.putExtra(PERCENTAGE, progressUpdate);
                sendBroadcast(testIntent);
            }
            result = Activity.RESULT_OK;
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        publishResults(output.getAbsolutePath(), result);
    }

    private void publishResults(String outputPath, int result) {
        Intent intent = new Intent(".MESSAGE_INTENT");
        intent.putExtra(FILEPATH, outputPath);
        intent.putExtra(RESULT, result);
        sendBroadcast(intent);
    }

}

and to call this service i would use:

Intent intent = new Intent(MainActivity.getAppContext(), DownloadService.class);
intent.putExtra(DownloadService.FILENAME, downloadFileName[item]);
intent.putExtra(DownloadService.URL, urlDownload[item]);
MainActivity.getAppContext().startService(intent);

now this allows user to download one file at a time, however if the user downloads another file, the second file will have to wait till the first file is done downloading. now what is happening in my case is: 1- First download FILE_1 is downloading, and in the status is says FILE_1. 2- User clicks a new file download, the status changes the first file name to the second file name, and waits till FILE_1 finishes download to start with FILE_2 however the active download is changed from FILE_1 to FILE_2.

questions: is there a way to call DownloadService multiple times for multiple files? is it possible to fix the problem i'm facing? treating download intent services as two different intents?

UPDATE I managed to solve this issue by assigning a unique Int ID per file, each ID will point to a position in the listview which displays the files being downloaded or queued, then i work with each file on it's own.


回答1:


Following code uses commons-io-2.4.jar library to make your work easy by handling low level data movements as you would focus on method in hand

URL someUrl = new URL("your url String"); //
File someFile = new File("your file, where you want to save the data");
FileUtils.copyURLToFile(someUrl, someFile );

if you want to call this statement few time to download different files from the server following code might give you an idea what you might want to do, but you will have to write it's equivalent code to run in android which you want to probably AsyncTask

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FileUtils;

public class DownloadTest {

    public static void main(String[] args) {

        Thread thread = new Thread(){
            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();
                try {
                    dowanloadFile(new URL("some url"), new File("some file"));
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        thread.start();


    }

    private static void dowanloadFile(URL url, File file){
        try {
            FileUtils.copyURLToFile(url, file );
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


来源:https://stackoverflow.com/questions/34242897/android-downloading-multiple-files-with-inputstream-fileoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!