【问题标题】:Android phone crashes on downloading video(mp4) fileAndroid 手机在下载视频 (mp4) 文件时崩溃
【发布时间】:2013-03-14 11:25:47
【问题描述】:

我希望我的应用从 url 下载视频。 现在我想将下载文件写入我的 SD 卡。

我尝试了一些不同的脚本,但没有收到android.os.NetworkOnMainThreadException 异常。但是我的应用程序崩溃了。 Download a file programatically on Android What is best way to download files from net programatically in android?

有人知道如何创建工作方法吗? 要解决这个异常,它必须是一个异步任务。

public static void downloadFile(String url, File outputFile) {
        try {
              URL u = new URL(url);
              URLConnection conn = u.openConnection();
              int contentLength = conn.getContentLength();

              DataInputStream stream = new DataInputStream(u.openStream());

                byte[] buffer = new byte[contentLength];
                stream.readFully(buffer);
                stream.close();

                DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
                fos.write(buffer);
                fos.flush();
                fos.close();
          } catch(Exception e) {
              Log.e("theple", "" + e);
          } 
    }

日志:

03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException

【问题讨论】:

  • 在此处粘贴您的日志。
  • 必须是异步任务。您只需要在后台线程中运行它。 AsyncTask 只是实现这一目标的一种方式。
  • @AleksG 你有一个例子让我让它工作吗?

标签: android asynchronous download task mp4


【解决方案1】:

我让它工作了,谢谢你的帮助。

我的代码:

public class FileDownloader extends AsyncTask<String, Integer, String>
{

    @Override
    protected String doInBackground(String... params)
    {
        try {
              URL u = new URL(params[0]);
              URLConnection conn = u.openConnection();
              int contentLength = conn.getContentLength();

              DataInputStream stream = new DataInputStream(u.openStream());

                byte[] buffer = new byte[contentLength];
                stream.readFully(buffer);
                stream.close();

                DataOutputStream fos = new DataOutputStream(new FileOutputStream(new File(params[1])));
                fos.write(buffer);
                fos.flush();
                fos.close();
          } catch(Exception e) {
              Log.e("theple", "" + e);
          } 
        return null;
    }
}

【讨论】:

    【解决方案2】:

    有很多方法可以执行下载,尽管为它创建了一个方法,你应该使用“线程,异步类或服务”,那个错误“主线程上的网络 是因为这个过程需要时间”。

    我正在展示使用 Async TaskService 的示例

    *

    *class DownloadFile extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100% progress bar
                int fileLength = connection.getContentLength();
                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
                byte data[] = new byte[1024];
                long total = 0;
                int count;
    
    
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;
        }** 
    
    
    And With Service 
    
    you can use : 
    
    
    
       class DownloadService extends IntentService {
            public static final int UPDATE_PROGRESS = 8344;
            public DownloadService() {
                super("DownloadService");
            }
            @Override
            protected void onHandleIntent(Intent intent) {
                String urlToDownload = intent.getStringExtra("url");
                ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
                try {
                    URL url = new URL(urlToDownload);
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    // this will be useful so that you can show a typical 0-100% progress bar
                    int fileLength = connection.getContentLength();
                    // download the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
                    byte data[] = new byte[1024];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        Bundle resultData = new Bundle();
                        resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                        receiver.send(UPDATE_PROGRESS, resultData);
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,100);
                receiver.send(UPDATE_PROGRESS, resultData);
            }
        }
    

    希望这对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多