Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用暂停、继续和停止等基本任务控件管理多个文件下载_Android_Download - Fatal编程技术网

Android 使用暂停、继续和停止等基本任务控件管理多个文件下载

Android 使用暂停、继续和停止等基本任务控件管理多个文件下载,android,download,Android,Download,我想在我的android应用程序中集成文件下载功能。我使用“IntentService”成功地实现了多个文件下载,但我无法控制文件下载。意味着使用当前代码,我只能开始文件下载,但无法暂停或停止某个特定的文件下载 我用来从服务器下载文件的源代码 public class FileDownloadService extends IntentService{ public static final String RESPONSE_MESSAGE = "myResponseMessage";

我想在我的android应用程序中集成文件下载功能。我使用“IntentService”成功地实现了多个文件下载,但我无法控制文件下载。意味着使用当前代码,我只能开始文件下载,但无法暂停或停止某个特定的文件下载

我用来从服务器下载文件的源代码

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's 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;
    }
}
答案与源代码将是非常有帮助的


提前感谢。

android下载管理器,具有多任务下载、恢复下载、流量计数器和暂停、继续和删除等基本任务控制

谢谢你的快速回复。让我试试你的源代码。@raja我试过给定的源代码,但是我在给定的库中发现了太多的bug。你能给我一些建议吗。!!再次感谢你的回答。
 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?