ourhose 2019-05-15 15:17 采纳率: 100%
浏览 550
已采纳

安卓开发:用输入输出流实现往sdcard下载文件时,下载到途中程序闪退,这是为什么?

用输入输出流实现往sdcard下载apk文件时,下载到途中程序闪退,有时候下载到28%,有时候到6%,每次不同,但都下载不成功程序就停止运行了。apk文件大小为10M,手机卡上的容量有300多M。代码如下:

public File getFileFromServer(String path, ProgressDialog pd) throws Exception{

        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);

            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total=0;
            while((len =bis.read(buffer)) > 0){
                fos.write(buffer, 0, len);
                total+= len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.flush();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }
  • 写回答

2条回答 默认 最新

  • 彩色葫芦娃 2019-05-16 21:53
    关注

    抛异常还是内存溢出,有闪退的日志吗?另外,耗时操作放到其他线程里去

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退