android 实现多线程下载

public void DownLoad(String urlString,int threadSize) throws UnknownHostException, IOException
    {
        URL url=new URL(urlString);
        HttpURLConnection con=(HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(5000);
   
    int filelength=con.getContentLength();//获得文件大小
    pb.setMax(filelength);//设置进度条最大值
   
   
    String fileName=urlString.substring(urlString.lastIndexOf('/')+1);//获得文件名
    File saveFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),fileName);
    RandomAccessFile accessFile=new RandomAccessFile(saveFile, "rwd");
    accessFile.setLength(filelength);//设置跟下载文件一样大小
    accessFile.close();
    //计算每个线程下载数
    int block=filelength%threadSize==0? filelength/threadSize : filelength/threadSize+1;
    for(int threadid=0;threadid<threadSize;threadid++)
    {
    new DownloadThread(url, saveFile, block, threadid).start();
    }
   
    }
    private class DownloadThread extends Thread{
    private URL url;
private File saveFile;
private int block;
private int threadid;
public DownloadThread(URL url, File saveFile, int block, int threadid) {
this.url = url;
this.saveFile = saveFile;
this.block = block;
this.threadid = threadid;
}


public void run() {
int startposition = threadid * block;//每个线程开始位置
int endposition = (threadid + 1 ) * block - 1;//每个线程结束位置
try {
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startposition);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("Range", "bytes="+ startposition+ "-"+ endposition);//从文件什么位置写入
InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
accessFile.write(buffer, 0, len);//写入数据
Message message=Message.obtain();
message.arg1=len;
handler.sendMessage(message);//通知Handler更新进度条
}
inStream.close();
accessFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 实现多线程下载安装主要需要以下步骤: 1. 获取下载链接和文件名:在下载之前,需要先获取下载链接和文件名。 2. 创建多个线程:每个线程负责下载文件的一部分。这里可以使用 Java 的线程池技术,通过线程池管理多个线程。 3. 下载文件:每个线程下载文件的一部分,并将下载的数据写入本地文件。 4. 合并文件:所有线程下载完成后,将下载的文件片段合并为完整的文件。 5. 安装应用:下载完成后,通过系统的 Intent 启动安装程序,将下载的应用安装到设备上。 下面是一个简单的示例代码: ``` public class DownloadTask { private static final int THREAD_COUNT = 3; // 线程数量 private String downloadUrl; // 下载链接 private String fileName; // 文件名 private String savePath; // 保存路径 private long fileSize; // 文件大小 private Context context; public DownloadTask(Context context, String downloadUrl, String fileName, String savePath) { this.context = context; this.downloadUrl = downloadUrl; this.fileName = fileName; this.savePath = savePath; } public void startDownload() { try { URL url = new URL(downloadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); fileSize = connection.getContentLength(); connection.disconnect(); RandomAccessFile file = new RandomAccessFile(savePath + fileName, "rw"); file.setLength(fileSize); file.close(); ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); long blockSize = fileSize / THREAD_COUNT; for (int i = 0; i < THREAD_COUNT; i++) { long start = i * blockSize; long end = (i + 1) * blockSize - 1; if (i == THREAD_COUNT - 1) { end = fileSize - 1; } DownloadThread thread = new DownloadThread(context, downloadUrl, savePath, fileName, start, end); executor.execute(thread); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } mergeFile(); installApk(); } catch (Exception e) { e.printStackTrace(); } } // 合并文件 private void mergeFile() throws IOException { File file = new File(savePath + fileName); FileOutputStream fos = new FileOutputStream(file); for (int i = 0; i < THREAD_COUNT; i++) { FileInputStream fis = new FileInputStream(savePath + fileName + ".part" + i); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } fis.close(); new File(savePath + fileName + ".part" + i).delete(); } fos.close(); } // 安装应用 private void installApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(savePath + fileName)), "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } class DownloadThread extends Thread { private static final int BUFFER_SIZE = 1024; private Context context; private String downloadUrl; private String savePath; private String fileName; private long start; private long end; public DownloadThread(Context context, String downloadUrl, String savePath, String fileName, long start, long end) { this.context = context; this.downloadUrl = downloadUrl; this.savePath = savePath; this.fileName = fileName; this.start = start; this.end = end; } @Override public void run() { try { URL url = new URL(downloadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setRequestProperty("Range", "bytes=" + start + "-" + end); File file = new File(savePath + fileName + ".part" + getId()); FileOutputStream fos = new FileOutputStream(file); InputStream is = connection.getInputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); is.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们创建了一个 `DownloadTask` 类来管理下载任务。`startDownload()` 方法启动下载任务,首先获取文件大小,并创建一个与文件大小相同的空文件。然后使用线程池创建多个线程下载文件的不同部分。每个线程下载完成后,将文件片段写入以该线程 ID 命名的临时文件中。所有线程结束后,将临时文件合并为完整的文件,并启动安装程序来安装应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值