在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → android 通过wifi传输文件的例子源码,参考茄子快传的原理

android 通过wifi传输文件的例子源码,参考茄子快传的原理

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:0.01M
  • 下载次数:102
  • 浏览次数:6377
  • 发布时间:2014-08-29
  • 实例类别:Android平台开发
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: Android 文件 wifi

实例介绍

【实例简介】
【实例截图】

【核心代码】

package pip.Wifi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;
import pip.Bluetooth.BluetoothCS;
import pip.Bluetooth.BluetoothFile;
import pip.Tool.UnitSize;
import wyf.wpf.NewMain;
import wyf.wpf.choosecontactlocal;
import wyf.wpf.importing;
import wyf.wpf.R;
import wyf.wpf.Constant;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WifiReceive extends Activity {

	private TextView ReceiveRemind = null;// 提醒客户用的text
	private RelativeLayout progresscontainer = null;// 包含进度条的layout
	private ProgressBar Cyclepb = null;// 等待对方连接圆形进度
	private ProgressBar Horipb = null;// 接受信息进度
	private CheckTimeoutThread m_CheckTimeoutThread = null;// 用于检测服务端等待超时的线程

	static List<Byte> Bl = new LinkedList<Byte>();
	static FileOutputStream Rev_Fs;

	private boadIpThread boadIP = null;
	private String username = null;
	private String MobileName = null;
	private String OpponentIP = null;

	private static final int CONFIRM = 11;
	public static final byte CONFIRM_FLAG = 0;
	public static final byte CANCEL_FLAG = 1;

	private DatagramSocket datasocket = null;
	private ServerSocket connectss = null;
	private Socket connectsocket = null;
	private ServerSocket getVcardss = null;
	private Socket getVcardsocket = null;

	private final Handler mHandler = new Handler() {
		Bundle b = null;

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WifiHelper.WIFICONNECT:
				showDialog(CONFIRM);// 调用onCreateDialog
				break;
			case WifiHelper.UDP_SEND:
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.udp_send));
				break;
			case Constant.SERVICE_ON:
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.server_start));
				break;
			case Constant.MESSAGE_CONNECTED:
				// 使用interrupt停止检测超时线程的运行
				m_CheckTimeoutThread.interrupt();
				m_CheckTimeoutThread = null;
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.receiving));
				progresscontainer.removeView(Cyclepb);
				break;
			case Constant.INIT_PROG:
				b = msg.getData();
				int max = b.getInt("Total");
				Horipb.setMax(max);
				RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT, // width
						ViewGroup.LayoutParams.WRAP_CONTENT // height

				);
				UnitSize.mysetMargins(WifiReceive.this, barlp, 0, 100, 0, 0);
				progresscontainer.addView(Horipb, barlp);

				Horipb.setVisibility(View.VISIBLE);
				break;
			case Constant.UPDATE_PROG:
				b = msg.getData();
				int progress = b.getInt("Progress");
				Horipb.setProgress(progress);
				break;
			case Constant.CONNECT_TIMEOUT:
				AlertDialog dlg4 = new AlertDialog.Builder(WifiReceive.this)
						.setTitle("超时操作").setMessage(
								"您已等待较长时间,是否返回重新操作?选择“是”返回,选择“否”继续等待。")
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										onBackPressed();
									}
								}).setNeutralButton("否",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int witch) {
										dialog.dismiss();
										// 监听后运行超时检测线程
										m_CheckTimeoutThread = new CheckTimeoutThread(
												mHandler);
										m_CheckTimeoutThread.start();
									}
								}).create();
				dlg4.show();
				break;
			case Constant.MESSAGE_RECEIVED:
				Horipb.setVisibility(View.INVISIBLE);
				Intent i = new Intent(WifiReceive.this, importing.class);
				i.putExtra("filepath", WifiHelper.WIFIRECEIVEPATH);
				startActivity(i);
				break;
			}
		}
	};

	/************** 提示对话框 ***************/
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CONFIRM:
			String tempstring = "您是否确认接受对方用户的链接请求:"   MobileName;
			return new AlertDialog.Builder(WifiReceive.this).setTitle("温馨提示")
					.setMessage(tempstring).setIcon(
							android.R.drawable.ic_dialog_info)
					.setPositiveButton("确认", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							SendResponseThread sp = new SendResponseThread(
									CONFIRM_FLAG);
							sp.start();
							// 启动接收线程
							ServerThread server = new ServerThread(mHandler);
							server.start();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							SendResponseThread sp = new SendResponseThread(
									CANCEL_FLAG);
							sp.start();
						}
					}).create();
		default:
			return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.btserverfetch);
		setContentView(R.layout.wifireceive);
		progresscontainer = (RelativeLayout) findViewById(R.id.progresscontainer);
		Horipb = (ProgressBar) findViewById(R.id.importbar);
		Cyclepb = (ProgressBar) findViewById(R.id.cyclebar);
		ReceiveRemind = (TextView) findViewById(R.id.btservertext);
		String ss = getString(R.string.building_server);

		progresscontainer.removeView(Horipb);
		ReceiveRemind.setText(ss);
		RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT, // width
				ViewGroup.LayoutParams.WRAP_CONTENT // height

		);
		UnitSize.mysetMargins(WifiReceive.this, barlp, 135, 100, 0, 0);
		progresscontainer.removeView(Cyclepb);
		progresscontainer.addView(Cyclepb, barlp);

		Cyclepb.setVisibility(View.VISIBLE);

		Intent intent = getIntent();
		username = intent.getStringExtra("username");

		DatagramSocket ds;
		try {
			ds = new DatagramSocket(WifiHelper.UDP_BOADCASTPORT);
			ds.setBroadcast(true);

			// 创建并启动发送线程
			boadIP = new boadIpThread(username, ds);
			boadIP.start();
			mHandler.obtainMessage(WifiHelper.UDP_SEND).sendToTarget();
		} catch (SocketException e1) {
			System.out.println("广播IP的Socket错了");
			e1.printStackTrace();
		} catch (Exception e) {
			System.out.println("广播IP的Socket错了");
			e.printStackTrace();
		}
		// 启动connect请求监听线程
		GetConnectThread connect = new GetConnectThread(mHandler);
		connect.start();

	}

	/**
	 * 广播自己用户名的线程
	 * 
	 * @author XijieChen
	 * 
	 */
	class boadIpThread extends Thread {

		private String username;

		public boadIpThread(String name, DatagramSocket dsocket)
				throws Exception {
			username = name;
			datasocket = dsocket;
		}

		public void run() {
			try {
				while (true) {
					// 构造发送数据报 把自己的名字发送出去
					byte[] data = username.getBytes();
					DatagramPacket outgoing = new DatagramPacket(data,
							data.length, InetAddress
									.getByName("255.255.255.255"),
							WifiHelper.UDP_BOADCASTPORT);
					// 发送数据报
					datasocket.send(outgoing);

					System.out.println("广播IP地址");
					Thread.sleep(1000);// 每秒广播一次
				}
			} catch (Exception ee) {
				System.out.println("广播IP地址的socket出错");
			} finally {
				// 关闭dsocket
				System.out.println("关闭广播IP地址的socket");

				if (datasocket != null)
					datasocket.close();
			}
		}
	}

	/***
	 * 监听发送方connect请求的线程
	 * 
	 * @author XijieChen
	 * 
	 */
	class GetConnectThread extends Thread {
		private InputStream instrm = null;
		private final Handler tHandler;

		GetConnectThread(Handler handler) {
			tHandler = handler;
		}

		public void run() {

			try {
				connectss = new ServerSocket(WifiHelper.TCP_CONNECTPORT);
				System.out.println("ConnectListening...");

				// accept阻塞直到被连接
				connectsocket = connectss.accept();
				System.out.println("ConnectThread Connected...");

				// 阻塞运行
				instrm = connectsocket.getInputStream();
				MobileName = getMobilename(instrm);
				tHandler.obtainMessage(WifiHelper.WIFICONNECT).sendToTarget();

				OpponentIP = connectsocket.getInetAddress().toString();
				OpponentIP = OpponentIP.substring(1);
				System.out.println("发送方的IP地址=="   OpponentIP);
				boadIP = null;// 终止boadIP线程,即停止广播
				datasocket.close();

			} catch (Exception e) {

				System.out.println("Connect请求线程出错");
				e.printStackTrace();
			}
		}
	}

	private String getMobilename(InputStream instrm) {

		byte[] buffer = new byte[WifiHelper.NAME_BUFFER_LENGTH];
		try {
			instrm.read(buffer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String newstr = new String(buffer);
		System.out.println("对方用户名=="   newstr);
		return newstr;
	}

	/**
	 * 向发送方发送响应的线程
	 * 
	 * @author XijieChen
	 * 
	 */
	class SendResponseThread extends Thread {

		private OutputStream outStrm = null;
		byte flag = 0;

		public SendResponseThread(byte FLAG) {
			flag = FLAG;
		}

		public void run() {
			try {
				// 阻塞运行
				outStrm = connectsocket.getOutputStream();
				outStrm.write(flag & 0x000000ff);
				System.out.println("发送响应的flag=="   flag);

				if (flag == CANCEL_FLAG) {
					onBackPressed();
				}
				outStrm.close();
				connectsocket.close();
				connectss.close();
			} catch (IOException e) {

				try {
					if (connectss != null)
						connectss.close();
					if (connectsocket != null)
						connectsocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {
					if (outStrm != null)
						outStrm.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private class CheckTimeoutThread extends Thread {
		Handler mhandler = null;

		CheckTimeoutThread(Handler mhandler) {
			this.mhandler = mhandler;
		}

		public void run() {
			try {
				Thread.sleep(WifiHelper.timecheck);
				mhandler.obtainMessage(Constant.CONNECT_TIMEOUT).sendToTarget();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			}
		}
	}

	/**
	 * 按照协议接收文件的线程
	 * 
	 * @author XijieChen
	 */
	class ServerThread extends Thread {

		private InputStream instrm = null;
		private OutputStream outstream = null;
		private final Handler tHandler;
		byte ack[] = new byte[3];// 这个ack数组是为了强制双方数据传递同步

		ServerThread(Handler handler) {
			tHandler = handler;
			ack[0] = 'a';
			ack[1] = 'c';
			ack[2] = 'k';
		}

		public void run() {
			byte headtype = 0;

			try {
				getVcardss = new ServerSocket(WifiHelper.TCP_TRANSMISSIONPORT);
				System.out.println("接收文件的Listening...");

				tHandler.obtainMessage(Constant.SERVICE_ON).sendToTarget();
				// 监听后运行超时检测线程
				m_CheckTimeoutThread = new CheckTimeoutThread(tHandler);
				m_CheckTimeoutThread.start();
				// accept阻塞直到被连接
				getVcardsocket = getVcardss.accept();
				System.out.println("接收Vcard的Client Connected...");

				tHandler.obtainMessage(Constant.MESSAGE_CONNECTED)
						.sendToTarget();
				// 阻塞运行
				instrm = getVcardsocket.getInputStream();
				headtype = (byte) instrm.read();

				outstream = getVcardsocket.getOutputStream();
				outstream.write(ack);

				Rev_Fs = new FileOutputStream(new File(
						WifiHelper.WIFIRECEIVEPATH));
				ReceiveContent(headtype, instrm, outstream, ack);

				tHandler.obtainMessage(Constant.MESSAGE_RECEIVED)
						.sendToTarget();
				getVcardsocket.close();
				getVcardss.close();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (getVcardsocket != null)
						getVcardsocket.close();
					if (getVcardss != null)
						getVcardss.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/************ 接收文件的内容 *************/
	private static void ReceiveContent(byte headtype, InputStream instrm,
			OutputStream outstream, byte ack[]) {

		if (headtype == BluetoothCS.END)
			return;
		byte lengthhighhigh, lengthhighlow, lengthlowhigh, lengthlowlow;
		try {
			System.out.println("从这里开始接收文件");
			// lengthhighhigh = (byte) instrm.read();
			// lengthhighlow = (byte) instrm.read();
			// lengthlowhigh = (byte) instrm.read();
			// lengthlowlow = (byte) instrm.read();
			byte[] lengthbyte = new byte[4];
			instrm.read(lengthbyte);
			lengthhighhigh = lengthbyte[3];
			lengthhighlow = lengthbyte[2];
			lengthlowhigh = lengthbyte[1];
			lengthlowlow = lengthbyte[0];

			int ContentLength = fourBytetoInt(lengthhighhigh, lengthhighlow,
					lengthlowhigh, lengthlowlow);

			System.out.println("length is "   ContentLength);

			outstream.write(ack);

			byte[] buffer = new byte[WifiHelper.WIFI_BUFFER_LENGTH];
			int left = ContentLength;
			int readonce = 0;
			while (left > 0) {
				readonce = instrm.read(buffer);
				outstream.write(ack);
				left = left - readonce;

				System.out.println("left1 length is "   left);
				Rev_Fs.write(buffer, 0, readonce);
				for (int i = 0; i < readonce; i  ) {
					Bl.add(new Byte(buffer[i]));
				}
				System.out.println("left2 length is "   left);
			}
			instrm.close();
			outstream.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			try {
				instrm.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

	}

	/************* 合并文件的高低字节以得到文件的长度 **************/
	public static int fourBytetoInt(byte Highhigh, byte Highlow, byte Lowhigh,
			byte Lowlow) {
		int Int = 0;
		Int = Highhigh;
		Int = (int) (Int << 24);
		Int = Int   (0x00FF0000 & ((int) Highlow << 16));
		Int = Int   (0x0000FF00 & ((int) Lowhigh << 8));
		Int = Int   (0x000000FF & ((int) Lowlow));
		return Int;
	}

	/*************** 点击了“返回”按钮 *****************/
	public void onmain(View view) {
		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// onBackPressed();
		Intent i = new Intent(WifiReceive.this, NewMain.class);
		i.setFlags(i.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	@Override
	protected void onStop() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onStop();
	}

	@Override
	public void onBackPressed() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onBackPressed();
	}

}

标签: Android 文件 wifi

实例下载地址

android 通过wifi传输文件的例子源码,参考茄子快传的原理

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 假装我在飞 发表于: 2016-05-17 14:26 29
这就不是一个项目工程,只有4个类文件,啥都干不了,上传的的作者不是偷窃就是shab。。。

支持(0) 盖楼(回复)

第 2 楼 假装我在飞 发表于: 2016-05-17 14:26 29
这就不是一个项目工程,只有4个类文件,啥都干不了,上传的的作者不是偷窃就是shab。。。

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有2条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警