android中之断点续传

此源码有助于理解;也是参照网上大神案例来改写的

源代码贴上


    

package com.xm.download;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	final String path="http://gdown.baidu.com/data/wisegame/775ed200394c4c3d/QQyinle_283.apk";
	final String pathName="QQyinle_283.apk";
	final int ThreadCount=3;
	static int finishedThread;
	int currentProgress;
	private ProgressBar pb;
	TextView tv;
	
	
	
	Handler handler=new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			if(msg.what==1)
			{
				//把变量改成long,在long下运算
				tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%");
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pb=(ProgressBar)findViewById(R.id.pb);
		tv=(TextView)findViewById(R.id.tv);
	}
	
	/**
	 * 
	 * @param v
	 */
	public void click(View v)
	{
		Thread ad=new Thread()
		{	
			@Override
			public void run() {
				//发送get请求
				try {
					URL url=new URL(path);
					HttpURLConnection huc=(HttpURLConnection)url.openConnection();
					huc.setRequestMethod("GET");
					huc.setConnectTimeout(5000);
					huc.setReadTimeout(5000);
					if(huc.getResponseCode()==200)//请求成功
					{
						int contentLenth=huc.getContentLength();//得到长度
						//设置进度条的最大长度为文件的长度
						pb.setMax(contentLenth);
						//生成临时文件
						File file=new File(Environment.getExternalStorageDirectory(),pathName);
						RandomAccessFile raf=new RandomAccessFile(file,"rwd");
						raf.setLength(contentLenth);//设置大小
						raf.close();
						//计算出每个区间的下载大小
						int size=contentLenth/ThreadCount;
						
						for(int i=0;i

最后;别忘了把权限加上哦

你可能感兴趣的:(android,android,源代码)