Android通过TCPIP协议实现断点续传上传实现

package cn.itcast.service;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {

	public DBOpenHelper(Context context) {
		super(context, "upload.db", null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE uploadlog (_id integer primary key autoincrement, uploadfilepath varchar(100), sourceid varchar(10))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS uploadlog");
		onCreate(db);		
	}

}

package cn.itcast.service;

import java.io.File;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class UploadLogService {
	private DBOpenHelper dbOpenHelper;
	
	public UploadLogService(Context context){
		this.dbOpenHelper = new DBOpenHelper(context);
	}
	
	public void save(String sourceid, File uploadFile){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.execSQL("insert into uploadlog(uploadfilepath, sourceid) values(?,?)",
				new Object[]{uploadFile.getAbsolutePath(),sourceid});
	}
	
	public void delete(File uploadFile){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.execSQL("delete from uploadlog where uploadfilepath=?", new Object[]{uploadFile.getAbsolutePath()});
	}
	
	public String getBindId(File uploadFile){
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select sourceid from uploadlog where uploadfilepath=?", 
				new String[]{uploadFile.getAbsolutePath()});
		if(cursor.moveToFirst()){
			return cursor.getString(0);
		}
		return null;
	}
}

package cn.itcast.video.upload;

import java.io.File;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.RandomAccessFile;
import java.net.Socket;

import cn.itcast.service.UploadLogService;
import cn.itcast.utils.StreamTool;

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.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UploadActivity extends Activity {
    private EditText filenameText;
    private TextView resulView;
    private ProgressBar uploadbar;
    private UploadLogService logService;
    private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			int length = msg.getData().getInt("size");
			uploadbar.setProgress(length);
			float num = (float)uploadbar.getProgress()/(float)uploadbar.getMax();
			int result = (int)(num * 100);
			resulView.setText(result+ "%");
			if(uploadbar.getProgress()==uploadbar.getMax()){
				Toast.makeText(UploadActivity.this, R.string.success, 1).show();
			}
		}
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        logService = new UploadLogService(this);
        filenameText = (EditText)this.findViewById(R.id.filename);
        uploadbar = (ProgressBar) this.findViewById(R.id.uploadbar);
        resulView = (TextView)this.findViewById(R.id.result);
        Button button =(Button)this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String filename = filenameText.getText().toString();
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					File uploadFile = new File(Environment.getExternalStorageDirectory(), filename);
					if(uploadFile.exists()){
						uploadFile(uploadFile);
					}else{
						Toast.makeText(UploadActivity.this, R.string.filenotexsit, 1).show();
					}
				}else{
					Toast.makeText(UploadActivity.this, R.string.sdcarderror, 1).show();
				}
			}
		});
    }
    /**
     * 上传文件
     * @param uploadFile
     */
	private void uploadFile(final File uploadFile) {
		new Thread(new Runnable() {			
			@Override
			public void run() {
				try {
					uploadbar.setMax((int)uploadFile.length());
					String souceid = logService.getBindId(uploadFile);
					String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+
						(souceid==null? "" : souceid)+"\r\n";
					Socket socket = new Socket("192.168.1.100", 7878);
					OutputStream outStream = socket.getOutputStream();
					outStream.write(head.getBytes());
					
					PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());	
					String response = StreamTool.readLine(inStream);
			        String[] items = response.split(";");
					String responseid = items[0].substring(items[0].indexOf("=")+1);
					String position = items[1].substring(items[1].indexOf("=")+1);
					if(souceid==null){//代表原来没有上传过此文件,往数据库添加一条绑定记录
						logService.save(responseid, uploadFile);
					}
					RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
					fileOutStream.seek(Integer.valueOf(position));
					byte[] buffer = new byte[1024];
					int len = -1;
					int length = Integer.valueOf(position);
					while( (len = fileOutStream.read(buffer)) != -1){
						outStream.write(buffer, 0, len);
						length += len;
						Message msg = new Message();
						msg.getData().putInt("size", length);
						handler.sendMessage(msg);
					}
					fileOutStream.close();
					outStream.close();
		            inStream.close();
		            socket.close();
		            if(length==uploadFile.length()) logService.delete(uploadFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

public class StreamTool {
	 
	 public static void save(File file, byte[] data) throws Exception {
		 FileOutputStream outStream = new FileOutputStream(file);
		 outStream.write(data);
		 outStream.close();
	 }
	 
	 public static String readLine(PushbackInputStream in) throws IOException {
			char buf[] = new char[128];
			int room = buf.length;
			int offset = 0;
			int c;
loop:		while (true) {
				switch (c = in.read()) {
					case -1:
					case '\n':
						break loop;
					case '\r':
						int c2 = in.read();
						if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
						break loop;
					default:
						if (--room < 0) {
							char[] lineBuffer = buf;
							buf = new char[offset + 128];
						    room = buf.length - offset - 1;
						    System.arraycopy(lineBuffer, 0, buf, 0, offset);
						   
						}
						buf[offset++] = (char) c;
						break;
				}
			}
			if ((c == -1) && (offset == 0)) return null;
			return String.copyValueOf(buf, 0, offset);
	}
	 
	/**
	* 读取流
	* @param inStream
	* @return 字节数组
	* @throws Exception
	*/
	public static byte[] readStream(InputStream inStream) throws Exception{
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			while( (len=inStream.read(buffer)) != -1){
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			return outSteam.toByteArray();
	}
}

项目源码下载: http://pan.baidu.com/share/link?shareid=267458&uk=1796216265

你可能感兴趣的:(Android)