簡體   English   中英

如何在Android中啟動和停止下載多個文件

[英]How to start and stop the download of multiple files in android

我有一個帶有按鈕和標簽的活動。 在按鈕上單擊我的應用程序必須下載幾個文件(大約9000個)。 如果用戶再次單擊按鈕,則下載必須停止,並且再次單擊必須從頭開始。

所以這就是我要做的:

活動中:

    file.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Button b = (Button)v;
            if(canFile){
                b.setText("Stop download");
                changeLabelInfo("Getting file list...");
                labelFile.setVisibility(View.VISIBLE);
                fileTask.start();
            }else{
                b.setText("Download files");
                if(fileTask.isAlive()){  
                   fileTask.interrupt();
                   fileTask = null;
                   fileTask = new UpdateFilesThread(this);
                }
                labelFile.setVisibility(View.INVISIBLE);
                Kernel.setManualUpdate("file",false);
            }
            canFile = !canFile;
        }
    });

必須下載文件的線程是UpdateFilesThread

public class UpdateFilesThread extends Thread{
    private MainActivity activity;
    private final String rootPath = "/mnt/local/";
    public UpdateFilesThread(MainActivity activity){
        this.activity = activity;
    }


    public void run(){
        String json = getFilesURL();
        JSONObject a = (JSONObject)JSONValue.parse(json);
        boolean isZip = false,canDownload = true;
        String[] keys = new String[]{"key1","key2","key3","key4"};

        for(String key:keys){
            Object folder = (Object)a.get(key);
            if(folder instanceof JSONObject){
                JSONObject fold = (JSONObject)folder;
                for(Object path_o:fold.keySet()){
                    path = path_o.toString().replace(" ", "%20");
                    if(local.endsWith(".php")){
                        isZip = true;
                        try {
                            Jsoup.connect(mywebserviceURL).data("path",path).timeout(0).post(); // If php generate zip containing php file
                        } catch (IOException e) {
                            canDownload = false;
                        }
                    }
                    if(canDownload){
                        try{
                            if(downloadFromUrl(path,isZip))
                                //SAVE URL DOWNLOADED
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                    canDownload = true;
                    isZip = false;
                }
            }
        }
        a.remove(key);
    }

    private String getFilesURL(){
        try {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("type", new StringBody("all"));
            HttpPost post = new HttpPost("mywebserviceURL");
            post.setEntity(entity);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(post);

            return EntityUtils.toString(response.getEntity());
        } catch (UnsupportedEncodingException e) {
            Support.writeError(e, null);
            e.printStackTrace();
            return "";
        } catch (ClientProtocolException e) {
            Support.writeError(e, null);
            e.printStackTrace();
            return "";
        } catch (ParseException e) {
            Support.writeError(e, null);
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            Support.writeError(e, null);
            e.printStackTrace();
            return "";
        }
    }
    public boolean downloadFromUrl(String path,boolean isZip){
        InputStream is = null;
        FileOutputStream fos = null;
        String localFilename = rootPath+path;
        String local = isZip?rootPath+"tmp.zip":localFilename;


        boolean return_ = false;
        try {
            URL url = new URL(isZip?mywebserviceURLZip:mywebserviceURLZip+path);
            URLConnection urlConn = url.openConnection();
            urlConn.setReadTimeout(0);
            is = urlConn.getInputStream();
            fos = new FileOutputStream(local);

            byte[] buffer = new byte[51200];
            int len;

            while ((len = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            is.close();
            if(isZip){
                ZipFile zip = new ZipFile(local);
                zip.extractAll(rootPath);
                new File(local).delete();
            }

            return_= true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return return_;
    }
}

當用戶單擊兩次按鈕時,我的問題就產生了(停止下載並重新開始)。 提示錯誤提示該線程已經開始並且正在運行中。我該如何解決? 我知道asyncTask應該會更好,但是我有問題,原因是我的應用程序中正在運行許多線程,而設備執行性能卻很差。是否可以肯定地停止線程? 還有其他更好的解決方案嗎?

嘗試實現AsyncTask 當用戶第一次點擊按鈕時,將調用任務的execute (Params... params) 在第二次點擊時調用任務的cancel (boolean mayInterruptIfRunning) 將下載功能放在任務的doInBackground (Params... params)

您的運行線程有時需要檢查isInterrupted()並在返回true時退出。 否則,該線程將永遠不會被取消。

我認為您的整個體系結構都是錯誤的。 將9000個文件下載到手機上? 即使每個文件只有1KB,對於移動應用程序來說,這也是巨大的內存。 至少出於您的理智,您應該壓縮這些數據並下載一個zip。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM