Manage multiple file downloads using basic task controls, such as pause, continue, and stop

I want to integrate the file upload function into an Android app. I have successfully implemented multiple file downloads using "IntentService", but I had no control over the file upload. Means with my current code. I can only start downloading a file, but I cannot pause or stop the download of a specific file.

The source code that I used to download the file from the server.

public class FileDownloadService extends IntentService{

    public static final String RESPONSE_MESSAGE = "myResponseMessage";  
    public static final String EXTRA_MESSAGE_LINK = "messageLink"; 
    public static final String EXTRA_MESSAGE_ID = "messageId"; 

    public ImageDownloadService() {
        super("ImageDownloadService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String msgLink =  intent.getStringExtra(EXTRA_MESSAGE_LINK);;
        String msgId =  intent.getStringExtra(EXTRA_MESSAGE_ID);;
        File msgFile = null;
        String responseMessage = "";
        int TIMEOUT_CONNECTION = 60000;// 6sec
        int TIMEOUT_SOCKET = 300000;// 3sec
        URLConnection ucon = null;
        URL url = null;

        try {
            url = new URL(Constant.URL + "ImageDownload?fileId="+msgLink);
            ucon = url.openConnection();

            // this timeout affects how long it takes for the app to realize
            // there a connection problem
            ucon.setReadTimeout(TIMEOUT_CONNECTION);
            ucon.setConnectTimeout(TIMEOUT_SOCKET);
            ucon.setRequestProperty("User-Agent", Constant.REQUEST_HEADER);

            String responseStatus = ucon.getHeaderField("status1");             
            if(responseStatus == null || !responseStatus.equalsIgnoreCase("success")){
                responseMessage = "Fail";
                updateAdapter(msgId, msgFile, responseMessage);
                return;
            }

            String fileLength = ucon.getHeaderField("filelength");              
            if(fileLength == null){
                responseMessage = "Fail";
                updateAdapter(msgId, msgFile, responseMessage);
                return;
            }
            InputStream is = null;
            is = ucon.getInputStream();

            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            FileOutputStream outStream = null;
            File file = null;

            try {
                msgFile = file = createImageFile();
                galleryAddPic(file);
                outStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                responseMessage = "Fail to create file in a Memory..";
                updateAdapter(msgId, msgFile, responseMessage);
                return;
            }

            byte[] buff = new byte[5 * 1024];
            int len;
//          int downloadedSize = 0;
            try {
                while ((len = inStream.read(buff)) != -1) {
                    outStream.write(buff, 0, len);
                //  downloadedSize += len;
                //  int progress = (int) (downloadedSize * 100 / totalSize);            
                }
                if(fileLength == null || file == null ){
                    updateAdapter(msgId, msgFile, "fail");
                }else if(fileLength.equalsIgnoreCase(""+file.length())){
                    updateAdapter(msgId, msgFile, "success");   
                }else{
                    if(file.exists()){
                        file.delete();
                    }
                    updateAdapter(msgId, msgFile, "fail");
                }
                return;
            } catch (IOException e) {
                e.printStackTrace();
                responseMessage= "fail";
                updateAdapter(msgId, msgFile, responseMessage);
                return;
            } finally{
                try {
                    outStream.flush();
                    if(outStream!=null ){
                        outStream.close();  
                    }
                    if(inStream!=null ){
                        inStream.close();   
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            responseMessage = "fail";
            updateAdapter(msgId, msgFile, responseMessage);
            return;
        }catch (IOException e1) {
            e1.printStackTrace();
            responseMessage = "fail";
            updateAdapter(msgId, msgFile, responseMessage);
            return;
        }catch(Exception e1) {
            e1.printStackTrace();
            responseMessage = "fail";
            updateAdapter(msgId, msgFile, responseMessage);
            return;
        }

    }

    private void updateAdapter(String msgId, File file, String response){
        DatabaseHandler db = DatabaseHandler.getInstance(this);

        if(response.equalsIgnoreCase("success")){
            MessageItem item = new MessageItem();
            try{
                galleryAddPic(file);
            }catch(Exception e){
                e.printStackTrace();
            }

            item.setId(msgId);
            item.setMessageInternalPath(file.getAbsolutePath());
            db.updateMessagePath(item);
        }else{

        }

        MessageItem message = new MessageItem();
        message.setId(msgId);
        message.setUploadRunningStatus(0);
        db.updateMessageRunningStatus(message);

        Intent broadcastIntent = new Intent("updateActivity");
        broadcastIntent.putExtra(RESPONSE_MESSAGE, response);
        sendBroadcast(broadcastIntent);
    }

    private void galleryAddPic(File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        sendBroadcast(mediaScanIntent);
    }

    private File createImageFile() {
        File mediaFile = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            mediaFile = new File(android.os.Environment.getExternalStorageDirectory(), "TEST" + File.separator + "Images"+File.separator +"IMAGE_"+System.currentTimeMillis()+".jpg");
            if (!mediaFile.exists()) {
                try {
                    mediaFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (!mediaFile.exists()) {
            File root = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "TEST" + File.separator + "Images" +File.separator );
            if (!root.exists()) {
                root.mkdirs();
            }
            String imageFileName = "IMAGE_"+System.currentTimeMillis();
            File image;
            try {
                image = File.createTempFile(imageFileName, /* prefix */
                        ".jpg", /* suffix */
                        root /* directory */
                );
                return image;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return mediaFile;
        }
        return null;
    }
}
 Question.
        1. How can i implement multiple file download feature with basic task controls such as pause, continue and stop ?
        2. Is there any library available using which i can control the file download?

The answer to the source code will be very helpful.

Thanks in advance.

+4
source share
1 answer

Android muti-, , , , .

0

All Articles