Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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
在android中下载大文件_Android_Multithreading_Download - Fatal编程技术网

在android中下载大文件

在android中下载大文件,android,multithreading,download,Android,Multithreading,Download,当我尝试此代码时,它会开始下载,但随后会出现警报“强制关闭” 我该怎么办?使用某种背景线程 try { long startTime = System.currentTimeMillis(); URL u = new URL("http://file.podfm.ru/3/33/332/3322/mp3/24785.mp3"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.se

当我尝试此代码时,它会开始下载,但随后会出现警报“强制关闭” 我该怎么办?使用某种背景线程

try {
    long startTime = System.currentTimeMillis();

    URL u = new URL("http://file.podfm.ru/3/33/332/3322/mp3/24785.mp3");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();

    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    FileOutputStream f = new FileOutputStream(new File("/sdcard/","logo.mp3"));

    InputStream in = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ( (len1 = in.read(buffer)) != -1 ) {
        f.write(buffer,0, len1);
    }
    f.close();

    Log.d("ImageManager", "download ready in" +
        ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
catch (IOException e)
{
    Log.d("ImageManager", "Error" +
        ((System.currentTimeMillis()) / 1000) + e + " sec");
}
你应该试着使用一种新的方法。您将获得“强制退出”对话框,因为您试图在UI线程上做太多工作,而Android判断您的应用程序已无响应

答案有一些好的链接

类似以下内容将是一个良好的开端:

private class DownloadLargeFileTask extends AsyncTask<Void, Void, Void> {
     private final ProgressDialog dialog;

     public DownloadLargeFileTask(ProgressDialog dialog) {
          this.dialog = dialog;
     }

     protected void onPreExecute() {
         dialog.show();
     }

     protected void doInBackground(Void... unused) {
         downloadLargeFile();
     }

     protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

上周我遇到了类似的问题,最后使用了进度条,因为下载文件可能需要一些时间。一种方法是将下面的类嵌套在
活动中
,只需在需要的地方调用它,如下所示:

new DownloadManager().execute("here be URL", "here be filename");
或者,如果该类不位于某个活动中,并且从某个活动调用

new DownloadManager(this).execute("URL", "filename");
这将传递活动,因此我们可以访问方法getSystemService()

下面是执行所有脏活的实际代码。您可能需要根据自己的需要对其进行修改

private class DownloadManager extends AsyncTask<String, Integer, Drawable>
{

    private Drawable d;
    private HttpURLConnection conn;
    private InputStream stream; //to read
    private ByteArrayOutputStream out; //to write
    private Context mCtx;

    private double fileSize;
    private double downloaded; // number of bytes downloaded
    private int status = DOWNLOADING; //status of current process

    private ProgressDialog progressDialog;

    private static final int MAX_BUFFER_SIZE = 1024; //1kb
    private static final int DOWNLOADING = 0;
    private static final int COMPLETE = 1;

    public DownloadManager(Context ctx)
    {
        d          = null;
        conn       = null;
        fileSize   = 0;
        downloaded = 0;
        status     = DOWNLOADING;
        mCtx       = ctx;
    }

    public boolean isOnline()
    {
        try
        {
            ConnectivityManager cm = (ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
        }
        catch (Exception e)
        {
            return false;
        }
    }

    @Override
    protected Drawable doInBackground(String... url)
    {
        try
        {
            String filename = url[1];
            if (isOnline())
            {
                conn     = (HttpURLConnection) new URL(url[0]).openConnection();
                fileSize = conn.getContentLength();
                out      = new ByteArrayOutputStream((int)fileSize);
                conn.connect();

                stream = conn.getInputStream();
                // loop with step
                while (status == DOWNLOADING)
                {
                    byte buffer[];

                    if (fileSize - downloaded > MAX_BUFFER_SIZE)
                    {
                        buffer = new byte[MAX_BUFFER_SIZE];
                    }
                    else
                    {
                        buffer = new byte[(int) (fileSize - downloaded)];
                    }
                    int read = stream.read(buffer);

                    if (read == -1)
                    {
                        publishProgress(100);
                        break;
                    }
                    // writing to buffer
                    out.write(buffer, 0, read);
                    downloaded += read;
                    // update progress bar
                    publishProgress((int) ((downloaded / fileSize) * 100));
                } // end of while

                if (status == DOWNLOADING)
                {
                    status = COMPLETE;
                }
                try
                {
                    FileOutputStream fos = new FileOutputStream(filename);
                    fos.write(out.toByteArray());
                    fos.close();
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    return null;
                }

                d = Drawable.createFromStream((InputStream) new ByteArrayInputStream(out.toByteArray()), "filename");
                return d;
            } // end of if isOnline
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }// end of catch
    } // end of class DownloadManager()

    @Override
    protected void onProgressUpdate(Integer... changed)
    {
        progressDialog.setProgress(changed[0]);
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog = new ProgressDialog(/*ShowContent.this*/); // your activity
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Downloading ...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Drawable result)
    {
        progressDialog.dismiss();
        // do something
    }
}
私有类下载管理器扩展异步任务
{
私人提款权;
专用HttpUrl连接连接;
私有InputStream;//读取
private ByteArrayOutputStream out;//写入
私有上下文mCtx;
私有双文件大小;
私有双下载;//下载的字节数
private int status=DOWNLOADING;//当前进程的状态
私有进程对话;
私有静态最终int MAX_BUFFER_SIZE=1024;//1kb
私有静态最终整数下载=0;
专用静态最终整型=1;
公共下载管理器(上下文ctx)
{
d=零;
conn=null;
fileSize=0;
下载=0;
状态=下载;
mCtx=ctx;
}
公共布尔isOnline()
{
尝试
{
ConnectivityManager cm=(ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_服务);
返回cm.getActiveNetworkInfo();
}
捕获(例外e)
{
返回false;
}
}
@凌驾
受保护的可绘制doInBackground(字符串…url)
{
尝试
{
字符串文件名=url[1];
if(isOnline())
{
conn=(HttpURLConnection)新URL(URL[0]).openConnection();
fileSize=conn.getContentLength();
out=newbytearrayoutputstream((int)fileSize);
连接();
stream=conn.getInputStream();
//步进环
while(状态==下载)
{
字节缓冲区[];
如果(文件大小-下载>最大缓冲区大小)
{
缓冲区=新字节[最大缓冲区大小];
}
其他的
{
缓冲区=新字节[(int)(文件大小-下载)];
}
int read=stream.read(缓冲区);
如果(读取==-1)
{
出版进度(100);
打破
}
//写入缓冲区
输出。写入(缓冲区,0,读取);
下载+=读取;
//更新进度条
出版进度((int)((下载/文件大小)*100));
}//时间结束
如果(状态==正在下载)
{
状态=完成;
}
尝试
{
FileOutputStream fos=新的FileOutputStream(文件名);
fos.write(out.toByteArray());
fos.close();
}
捕获(IOE异常)
{
e、 printStackTrace();
返回null;
}
d=Drawable.createFromStream((InputStream)new ByteArrayInputStream(out.toByteArray()),“filename”);
返回d;
}//if isOnline的结尾
其他的
{
返回null;
}
}
捕获(例外e)
{
e、 printStackTrace();
返回null;
}//捕获结束
}//类结束下载管理器()
@凌驾
受保护的void onProgressUpdate(整数…已更改)
{
progressDialog.setProgress(更改为[0]);
}
@凌驾
受保护的void onPreExecute()
{
progressDialog=新建progressDialog(/*ShowContent.this*/);//您的活动
progressDialog.setProgressStyle(progressDialog.STYLE_水平);
progressDialog.setMessage(“下载…”);
progressDialog.setCancelable(假);
progressDialog.show();
}
@凌驾
受保护的void onPostExecute(可提取结果)
{
progressDialog.disclose();
//做点什么
}
}
private class DownloadManager extends AsyncTask<String, Integer, Drawable>
{

    private Drawable d;
    private HttpURLConnection conn;
    private InputStream stream; //to read
    private ByteArrayOutputStream out; //to write
    private Context mCtx;

    private double fileSize;
    private double downloaded; // number of bytes downloaded
    private int status = DOWNLOADING; //status of current process

    private ProgressDialog progressDialog;

    private static final int MAX_BUFFER_SIZE = 1024; //1kb
    private static final int DOWNLOADING = 0;
    private static final int COMPLETE = 1;

    public DownloadManager(Context ctx)
    {
        d          = null;
        conn       = null;
        fileSize   = 0;
        downloaded = 0;
        status     = DOWNLOADING;
        mCtx       = ctx;
    }

    public boolean isOnline()
    {
        try
        {
            ConnectivityManager cm = (ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
        }
        catch (Exception e)
        {
            return false;
        }
    }

    @Override
    protected Drawable doInBackground(String... url)
    {
        try
        {
            String filename = url[1];
            if (isOnline())
            {
                conn     = (HttpURLConnection) new URL(url[0]).openConnection();
                fileSize = conn.getContentLength();
                out      = new ByteArrayOutputStream((int)fileSize);
                conn.connect();

                stream = conn.getInputStream();
                // loop with step
                while (status == DOWNLOADING)
                {
                    byte buffer[];

                    if (fileSize - downloaded > MAX_BUFFER_SIZE)
                    {
                        buffer = new byte[MAX_BUFFER_SIZE];
                    }
                    else
                    {
                        buffer = new byte[(int) (fileSize - downloaded)];
                    }
                    int read = stream.read(buffer);

                    if (read == -1)
                    {
                        publishProgress(100);
                        break;
                    }
                    // writing to buffer
                    out.write(buffer, 0, read);
                    downloaded += read;
                    // update progress bar
                    publishProgress((int) ((downloaded / fileSize) * 100));
                } // end of while

                if (status == DOWNLOADING)
                {
                    status = COMPLETE;
                }
                try
                {
                    FileOutputStream fos = new FileOutputStream(filename);
                    fos.write(out.toByteArray());
                    fos.close();
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    return null;
                }

                d = Drawable.createFromStream((InputStream) new ByteArrayInputStream(out.toByteArray()), "filename");
                return d;
            } // end of if isOnline
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }// end of catch
    } // end of class DownloadManager()

    @Override
    protected void onProgressUpdate(Integer... changed)
    {
        progressDialog.setProgress(changed[0]);
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog = new ProgressDialog(/*ShowContent.this*/); // your activity
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Downloading ...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Drawable result)
    {
        progressDialog.dismiss();
        // do something
    }
}