0

我有一个带有按钮和标签的活动。在按钮上单击我的应用程序必须下载几个文件(大约 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 应该更好,但我有问题,因为在我的应用程序中有这么多线程正在运行,并且设备性能很差.. 有可能完全停止一个线程吗?还有其他更好的解决方案吗?

4

2 回答 2

1

尝试实现AsyncTask。当用户第一次点击按钮时,调用任务的execute (Params... params). 在第二次点击时调用任务的cancel (boolean mayInterruptIfRunning). 将下载功能放在任务的doInBackground (Params... params)

于 2013-02-11T18:01:24.643 回答
0

您的运行线程需要偶尔检查 isInterrupted() 并在返回 true 时退出。否则线程将永远不会被取消。

我认为你的整个架构是错误的。将9000个文件下载到手机上?即使每个文件只有 1KB,这对于移动应用程序来说也是巨大的内存量。至少你应该压缩这些数据并下载一个压缩包,为了你自己的理智。

于 2013-02-11T16:40:37.850 回答