Android:从网址下载

时间:2015-01-13 19:29:19

标签: android

我在本网站上关注下载mp3或图片来自URL更多解释,我按照更多方法尝试编写我的方法但是当我运行应用程序时它会停止。

点击
时,我制作查询下载的方法 同时也允许INTERNET& WRITE_EXTERNAL_STORAGE

把问题还是

此方法是下载

public static void downloadMain(){
    File fileToSave = null;
    String scrPath ="http://***";
    BufferedInputStream bis;
    BufferedOutputStream bos;

    fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A"+"/");
    if (!fileToSave.exists())
        fileToSave.mkdirs();
    fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A" +"/" + "h"+"/");
    if (!fileToSave.exists())
        fileToSave.mkdirs();
    File file = new File (fileToSave,"***.mp3");
    try{
        URL url = new URL(scrPath+"***.mp3");
        URLConnection ucon = url.openConnection();
        ucon.connect();
        bis=new BufferedInputStream(ucon.getInputStream());

        bos = new BufferedOutputStream(new FileOutputStream(file));
        bis=new BufferedInputStream(url.openStream());
        byte[] data = new byte[1024];
        int a =0;
        while(true){
            int k = bis.read(data);
            if(k==-1){
                bis.close();
                bos.flush();
                bos.close();

                break;
            }
            bos.write(data, 0, k);
            a+=k;
        }
    }catch(IOException e){}
}

1 个答案:

答案 0 :(得分:0)

我对你的计划有三个主要的困惑:

  1. 您是否在asynctask中运行以下代码? (这必须按原样运行,否则会阻止)
  2. 为什么它无限循环?
  3. 您无法打开其中包含“*”的网址或文件
  4. 修改

    你必须运行下载方法,否则它将无效,无法在主线程中与文件系统和网络进行交互

    <强> EDIT2:

    AsyncTask应该是这样的

    private class DownloadTask extends AsyncTask<String, Integer, String> {
    
     private Context context;
    
        public DownloadTask(Context context) {
            this.context = context;
        }
    
        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
    
                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }
    
                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream("/sdcard/file_name.extension");//put here your path and your mkdirs
    
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
    
                    total += count;
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
    
                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }
     @Override
        protected void onPostExecute(String result) {
            if (result != null)
                Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
        }
    }
    

    你可以这样称呼它

    DownloadTask downloadTask = new DownloadTask(YourActivity.this);
    downloadTask.execute("the url to the file you want to download");
    

    您还可以查看此answer