Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.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
Java 如何在android中启动和停止下载多个文件_Java_Android_Multithreading - Fatal编程技术网

Java 如何在android中启动和停止下载多个文件

Java 如何在android中启动和停止下载多个文件,java,android,multithreading,Java,Android,Multithreading,我有一个带按钮和标签的活动。 按一下按钮,我的应用程序必须下载几个文件(约9000)。 如果用户再次单击按钮,下载必须停止,再次单击则必须从头开始 我就是这么做的: 在活动中: file.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Button b = (Button)v; if(canF

我有一个带按钮和标签的活动。 按一下按钮,我的应用程序必须下载几个文件(约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;
        }
    });
必须下载文件的线程是
updateFileThread

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应该更好,但我遇到了一个问题,因为我的应用程序中有太多线程在运行,而设备的性能太差。。
有可能完全停止一根线吗?还有其他更好的解决方案吗?

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


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

尝试实现一个压缩包。当用户第一次点击按钮时,调用任务的。在第二次点击时,调用任务的。将下载功能放在任务的

中这不是问题。。此应用程序将在我所在城市的许多平板电脑上运行,只需执行此应用程序。。。那么,你对更好的架构有什么建议吗?