安卓(Android) 怎么从url下载apk文件

2019年10月17日21:19:19安卓(Android) 怎么从url下载apk文件已关闭评论 964 963字阅读3分12秒

1.简介

安卓(Android) 怎么从url下载apk文件?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;
import android.app.ProgressDialog;
import android.os.Environment;

public class Main {
    public static File getApkFile(String url, ProgressDialog pd) {

        int last = url.lastIndexOf("/");
        File file = new File(Environment.getExternalStorageDirectory(),
                url.substring(last + 1));
        try {
            URL u = new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(5000);
            if (con.getResponseCode() == 200) {
                pd.setMax(con.getContentLength());
                int num = 0;
                InputStream is = con.getInputStream();
                FileOutputStream os = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                    num += len;
                    Thread.sleep(30);
                    pd.setProgress(num);
                }
                os.flush();
                os.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}

 
继续阅读
编程十万个怎么办