Android:无法从服务器下载文件

时间:2014-12-30 05:34:44

标签: android download httpurlconnection

我想从Server(Parse)下载文件(文档)。下载按钮显示在listview中,并按如下方式调用downloadFile方法:

setOnClickListener:

            holder.btn_dl.setOnClickListener(new View.OnClickListener() 
            {
                public void onClick(View v) 
                {
                    downloadFile(file_url_list[position], "aaa");
                }
            });

方法:

void downloadFile(String download_file_path, String file_name)
{
    String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYFOLDER/";
    try {
        URL url = new URL(download_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();

        File SDCardRoot = Environment.getExternalStorageDirectory();       
        File file = new File(fullPath, file_name);
        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();
        totalSize = urlConnection.getContentLength();
        showProgressdialog(download_file_path);
        getActivity().runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                pb.setMax(totalSize);
            }               
        });

        //create a buffer...
        byte[] buffer = new byte[2048];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
        {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            getActivity().runOnUiThread(new Runnable() 
            {
                public void run() 
                {
                    pb.setProgress(downloadedSize);
                    float per = ((float)downloadedSize/totalSize) * 100;
                    tv_download_message.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                }
            });
        }
        fileOutput.close();
        getActivity().runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                // pb.dismiss(); // if you want close it..
            }
        });         

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);        
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);          
        e.printStackTrace();
    }
    catch (final Exception e) {
        showError("Error : Please check your internet connection " + e);
    }       
}

void showError(final String err)
{
    getActivity().runOnUiThread(new Runnable() 
    {
        public void run() 
        {
            Toast.makeText(getActivity(), err, Toast.LENGTH_LONG).show();
        }
    });
}

void showProgressdialog(String file_path)
{
    dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_file_download);
    dialog.setTitle("Download Progress");

    TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);        
    tv_title.setText("Download file... ");

    tv_download_message = (TextView) dialog.findViewById(R.id.tv_download_message);
    tv_download_message.setText("Starting download...");    

    TextView tv_download_path = (TextView) dialog.findViewById(R.id.tv_download_path);
    tv_download_path.setText(""+file_path);
    tv_download_path.setMovementMethod(LinkMovementMethod.getInstance());

    dialog.show();

    pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    pb.setProgress(0);
    pb.setProgressDrawable(getResources().getDrawable(R.drawable.progress_green));  
}   

问题:

我在网络浏览器中尝试了file_url_list[position]的链接。链接工作得很好,文件可以成功下载到我的desltop。

但是,单击btn_dl无法下载该文件,并提供以下错误消息:

Error: Please check your internet connection. android.os.NetworkOnMainThreadException

PS:仔细检查是否有良好的互联网连接

1 个答案:

答案 0 :(得分:0)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行代码:

class downloadFile extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params) 
        {
            downloadFile(file_url_list[position], "aaa");
            return null;
        }

    }

new downloadFile().execute();

<uses-permission android:name="android.permission.INTERNET"/>