下载服务停止下载50%

时间:2018-12-29 20:38:48

标签: java android

我有用于从服务器下载文件APK 20 MB的应用程序,但问题下载过程在50%或60%的时间内停止,文件大小错误,无法安装应用程序。有什么帮助吗?我尝试了一些解决方案,例如添加 设置“连接超时”。

这是我的代码

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

0 个答案:

没有答案