`

支持断点续传的android代码

 
阅读更多
package com.nico;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.configue.Const;
import com.download.DownloadService;
import com.download.DownloadService.MyDownLoadThread;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DownLoadPage extends Activity implements OnClickListener {

	Br receiver = null;

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(receiver);
		Const.isDownloading = false;
	}

	private ProgressBar pb;
	private TextView txt;
	private NotificationManager nm;
	private Button btn;
	public DownloadService ds = new DownloadService();
	int percent = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		Intent intent = new Intent(DownLoadPage.this, DownloadService.class);
		Bundle bd = new Bundle();
		bd.putString("path", Environment.getExternalStorageDirectory()
				.getAbsolutePath());
		bd.putString("url", Const.url + "test.rar");
		intent.putExtras(bd);
		startService(intent);

		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		setContentView(R.layout.downloadpage);
		pb = (ProgressBar) findViewById(R.id.progressbar);
		txt = (TextView) findViewById(R.id.loadingtips);

		btn = (Button) findViewById(R.id.btn);
		btn.setText("停止下载");
		btn.setOnClickListener(this);
		receiver = new Br();
		IntentFilter intentfilter = new IntentFilter();
		intentfilter.addAction("com.nico.downloadpage");

		this.registerReceiver(receiver, intentfilter);
		showNotify();

	}

	public class Br extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			percent = intent.getIntExtra("percent", 0);
			pb.setProgress(percent);
			txt.setText(percent + "%");

			if (percent == 100) {
				txt.setText("下载完成");
				btn.setText("下载完成");
				nm.cancel(11111);
			}
		}

	}

	public void showNotify() {
		Notification ntf = new Notification(R.drawable.icon, "下载", System
				.currentTimeMillis());
		Intent i = new Intent();
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);

		PendingIntent intent = PendingIntent.getActivity(this, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);
		ntf.setLatestEventInfo(DownLoadPage.this, "下载", "正在下载", intent);
		nm.notify(11111, ntf);

	}

	@Override
	public void onClick(View v) {

		if (v == btn) {
			if (percent < 100 && percent > 0 && Const.isDownloading) {
				btn.setText("下载");
				stopService(new Intent(DownLoadPage.this, DownloadService.class));
			} else if (percent == 100) {
				btn.setText("下载完成");
				Const.isDownloading = false;
				btn.setClickable(false);
			} else {
				btn.setText("停止下载");
				Const.isDownloading = true;
				startService(new Intent(DownLoadPage.this,
						DownloadService.class));

			}

		}
	}

}





package com.download;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.RandomAccess;

import com.configue.Const;
import com.nico.DownLoadPage;
import com.nico.FileListView;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class DownloadService extends Service {

	@Override
	public void onDestroy() {
		Const.isDownloading = false;
		super.onDestroy();
	}

	private int percent;

	String fileUrl;
	int fileSize;
	boolean isFinish;
	String tempFile;
	File localFile;

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public void onStart(Intent intent, int startId) {

		Bundle bundle = intent.getExtras();
		String path1 ="";
		String url1 = "";
		if (bundle != null) {

			path1 = bundle.getString("path");
			Const.path = path1;
			url1 = bundle.getString("url");
			Const.fileurl = url1;
		} 

		fileUrl = Const.fileurl;
		tempFile = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
		localFile = new File(Const.path + "/" + tempFile);

		if (!localFile.exists()) {
			if (Const.isDownloading) {
				try {
					localFile.createNewFile();
					Const.downloadsize = 0;
					new MyDownLoadThread().start();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			Const.downloadsize = (int) localFile.length();
		
			int tempSize = getFileRealSize(fileUrl);
			if (Const.isDownloading) {
				if (Const.downloadsize != tempSize) {
					new MyDownLoadThread().start();
				}
			}
		}

	}

	@Override
	public boolean onUnbind(Intent intent) {

		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public long remoteFile() {

		return Const.downloadsize;
	}

	public class MyDownLoadThread extends Thread {

		byte[] perSize = new byte[512];
		FileOutputStream fos = null;
		InputStream is = null;
		HttpURLConnection conn = null;

		public MyDownLoadThread() {

		}

		@Override
		public void run() {
			RandomAccessFile  randomAccessFile = null;
			try {
				URL u = new URL(fileUrl);

				try {
					conn = (HttpURLConnection) u.openConnection();
					conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)");

					String sProperty = "bytes=" + Const.downloadsize + "-";


					conn.setRequestProperty("RANGE", sProperty);
					               randomAccessFile = new RandomAccessFile(localFile, "rwd");
					 
	                               randomAccessFile.seek(Const.downloadsize);


					fileSize = conn.getContentLength();
					conn.connect();
					is = conn.getInputStream();

					int realsize = getFileRealSize(fileUrl);
					int readSize = 0;
					int length = 0;
					int read = 0;
					while (Const.isDownloading
							&& (read = is.read(perSize, 0, 512)) != -1) {
						length = read;
						readSize += read;

						randomAccessFile.write(perSize, 0, length);
						percent = (int) ((localFile.length()+length) * 100 / realsize);
						Const.downloadsize += length;
						Intent intent = new Intent();
						intent.setAction("com.nico.downloadpage");
						if (Const.downloadsize == realsize) {
							isFinish = true;
							Const.isDownloading = false;
							percent = 100;

							intent.putExtra("percent", percent);
							DownloadService.this.sendBroadcast(intent);
							break;
						}

						intent.putExtra("percent", percent);

						for (int i = 0; i < 10000; i++) {
							if (i == 9999) {
								DownloadService.this.sendBroadcast(intent);
							}
						}
					}

				} catch (IOException e) {
					Const.isDownloading = false;
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				Const.isDownloading = false;
				e.printStackTrace();
			} finally {
				if (randomAccessFile != null) {
					try {
						randomAccessFile.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (conn != null) {
					conn.disconnect();
				}
			}
		}

	}
	
	
	public int getFileRealSize(String url)
	{
		URL u = null;
		try {
			u = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection connn = null;
		try {
			connn = (HttpURLConnection) u.openConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
		int tempSize = connn.getContentLength();
		return tempSize;
	}

}




package com.nico;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.configue.Const;
import com.enetity.FileBean;
import com.util.HttpConn;

public class FileListView extends Activity {

	private List<FileBean> list = null;
	private String url = Const.url+"file.xml";
	private ListView listview = null;

	private ProgressDialog pd = null;
	private String path;

	private ProgressBar pb = null;
	private Handler handler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			switch (msg.what) {
			case 1:
				list = new HttpConn().getData(url);
				break;
			case 2:
				Intent intent = new Intent(FileListView.this,
						DownLoadPage.class);
				startActivity(intent);	

				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		pd = new ProgressDialog(this);
		pd.setTitle("请等待");
		pd.setMessage("正在跳转请稍后");
		listview = (ListView) findViewById(R.id.listview);
		new getListAsynTask().execute();

		path = Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView img = null;
			TextView txt = null;
			Button btn = null;
			if (convertView == null) {
				convertView = FileListView.this.getLayoutInflater().inflate(
						R.layout.item, null);
			}
			img = (ImageView) convertView.findViewById(R.id.fileimg);
			txt = (TextView) convertView.findViewById(R.id.filename);
			btn = (Button) convertView.findViewById(R.id.downbtn);
			btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(Const.isNotLoad(Environment
						.getExternalStorageDirectory().getAbsolutePath(), Const.url+"test.rar"))
						
					{
//						Intent intent = new Intent(FileListView.this,
//								DownLoadPage.class);
//						startActivity(intent);
						handler.sendEmptyMessage(2);
					}
					else
					{
						Toast.makeText(FileListView.this, "文件已下载", 5000).show();
					}

					
				}
			});
			return convertView;
		}

	}

	public class getListAsynTask extends
			AsyncTask<String, String, List<FileBean>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd.show();
		}

		@Override
		protected void onPostExecute(List<FileBean> result) {
			super.onPostExecute(result);
			listview.setAdapter(new MyAdapter());
			pd.dismiss();
		}

		@Override
		protected List<FileBean> doInBackground(String... params) {
			list = new HttpConn().getData(url);
			return list;
		}

	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics