首页 > 解决方案 > 下载服务停止下载 50%

问题描述

我有从服务器下载文件 apk 20 MB 的应用程序,但问题下载过程有时会在 50% 或 60% 处停止,并且文件大小错误并且无法安装应用程序。有什么帮助吗?我尝试了一些解决方案,例如添加 set Connect Timeout 。

这是我的代码

       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);

        String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(String.valueOf(url));

        String name_file = URLUtil.guessFileName(String.valueOf(url), null, fileExtenstion);
        URLConnection connection = url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

        InputStream input = new BufferedInputStream(connection.getInputStream());

        OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+"/Appt/" + name_file);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;

            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);
}

标签: javaandroid

解决方案


推荐阅读