上图
先说说大致的布局框架吧!
主页面使用tablayout+viewpager实现,
因为TabLayout和ViewPager分别是属于design和v4包下的,所以我们先在app的build.gradle中添加:
compile 'com.android.support:design:23.1.1'
然后具体的布局就自己解决吧!
如果布局不懂就看这个博客吧
http://www.jianshu.com/p/adf7a994613a
传输
这个页面不多说
发现
发现模块是一个fragment,里面一样放了tablayout+viewpager+fragment。listview里面放的是design包下面的cardview,看起来新闻也挺美观的,点击进去是一个activity,里面写了一个Webview和进度条,具体新闻是通过聚合数据解析的。
记录
里面是一个gridview里面放的item,主要是传输完后的文件浏览
下面是一个自定义view的圆心统计表,记录接收的流量和发送的流量。
我要发送
进去使用contentprovider扫描手机里面的音乐、视频、图片,自制的一个简单的文件管理器
好了下面进入正题
我们需要使用面对面快传,就是一个手机开热点一个手机开wifi,组件成一个局域网,然后一个手机当client,一个手机当server。所以我们的问题是两个:
1.wifi的连接。
2.数据的传输。
然后我们来一个一个实现
1.wifi的连接
首先需要打开和关闭wifi
下面是app所有需要的权限
<!-- 创建和删除 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /><!-- 写入数据 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.GET_PACKAGE_SIZE" /><!-- 从SDCard读取数据权限 --><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><!-- 以下是使用wifi访问网络所需要的权限 --><!-- 修改网络状态的权限 --><uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /><!-- 修改wifi状态的权限 --><uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /><!-- 访问wifi权限 --><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><!-- 访问网络状态权限 --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><!-- 访问网络权限 --><uses-permission android:name="android.permission.INTERNET" />
关于wifi我自己封装了一些类
所以我就放出主要的调用代码
打开wifi并且连接到wifi
public class is_Sending extends Activity implements View.OnClickListener {private WifiLib wifiLib;//wifi管理类private String connectSsid = "My_kuaichuan";//热点名字private boolean isSuccess;private TextView textIsConnect;boolean flag = true;private String received_date;private RadarView radarView;private Button send_button;private Button research_button;private void assignViews() {research_button = (Button) findViewById(R.id.research_button);research_button.setOnClickListener(this);View title = findViewById(R.id.title);Button button = (Button) title.findViewById(R.id.back_button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {finish();}});TextView textView = (TextView) title.findViewById(R.id.title_tv);textView.setText("连接");TextView textView1 = (TextView) title.findViewById(R.id.title_lianjie);textView1.setText("连接不上?");textView1.setVisibility(View.VISIBLE);textView1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(is_Sending.this);builder.setTitle("连接不上");builder.setIcon(R.drawable.lw);builder.setMessage("如果连接不上My_kuaichuan可以手动连接,密码为12345678,再打开该应用,重新连接设备即可!");builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create();builder.show();}});textIsConnect = (TextView) findViewById(R.id.text_is_connect);radarView = (RadarView) findViewById(R.id.RadarView);radarView.setSearching(true);send_button = (Button) findViewById(R.id.send_button);send_button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {finish();}});}Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if (msg.what == 1) {//连接上了设备后将connected设置为true,并更新界面提示连接成功,显示发送按钮SharedPreferences.Editor editor = getSharedPreferences("judge",MODE_PRIVATE).edit();editor.putBoolean("connected", true);editor.commit();textIsConnect.setText("连接成功!");radarView.setSearching(false);//停止扫描动画send_button.setVisibility(View.VISIBLE);}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.is__sending);getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//沉浸状态栏assignViews();//wifi初始化WifiLibInitializer.init(this);wifiLib = WifiLib.getInstance();boolean b = wifiLib.openWifi();//开启wifiwifiLib.setOnWifiBroadcastReceiveCallback(callback);//连接上了设置监听wifiLib.startScan(500);//扫描wifi,时间间隔0.5snew Thread(runnable1).start();//开启接收者}private WifiBroadcastReceiver.OnWifiBroadcastReceiveCallback callback = new WifiBroadcastReceiver.OnWifiBroadcastReceiveCallback() {public void onScanResultsAvailable(java.util.List<AccessPoint> accessPoints) {WifiUtils.printAccessPoints(accessPoints);for (int i = 0; i < accessPoints.size(); i++) {AccessPoint ap = accessPoints.get(i);if (!TextUtils.isEmpty(connectSsid)&& ap.getSsid().equals(connectSsid)) {//如果遍历到了下面点击了连接给的ssid就会执行开始连接isSuccess = wifiLib.connectToAccessPoint(ap,"12345678");Log.i("HCY", isSuccess ? "连接热点成功" : "连接热点失败");//三木运算符if (isSuccess) {textIsConnect.setText("正在尝试连接");new Thread(runnable).start();//开启了wifi然后开启发送udp广播,当对方接收到了广播就会回播一条数据告诉我已经成功连接} else {textIsConnect.setText("连接热点失败");}wifiLib.stopScan();//连接成功停止扫描}}};};Runnable runnable = new Runnable() {@Overridepublic void run() {while (flag) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}send(getip(), "1");//发送udp广播给对方}}};Runnable runnable1 = new Runnable() {@Overridepublic void run() {receive();}};//接收对方回发的udp广播public void receive() {// 创建接收端的Socket对象DatagramSocket ds = null;try {ds = new DatagramSocket(54321);while (true) {// 创建一个包裹byte[] bys = new byte[1024];DatagramPacket dp = new DatagramPacket(bys, bys.length);// 接收数据ds.receive(dp);// 解析数据String ip = dp.getAddress().getHostAddress();received_date = new String(dp.getData(), 0, dp.getLength());System.out.println("from " + ip + " data is : " + received_date);if (received_date.equals("11111")) {flag = false;handler.sendEmptyMessage(1);}}// 释放资源// 接收端应该一直开着等待接收数据,是不需要关闭// ds.close();} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//连接上发送udp广播public void send(String ip, String text) {// 创建发送端Socket对象// DatagramSocket()DatagramSocket ds = null;try {ds = new DatagramSocket();// 创建数据,并把数据打包// DatagramPacket(byte[] buf, int length, InetAddress address, int port)// 创建数据byte[] bys = text.getBytes();// 长度int length = bys.length;// IP地址对象System.out.println(ip);InetAddress address = InetAddress.getByName(ip);// 端口int port = 10086;DatagramPacket dp = new DatagramPacket(bys, length, address, port);// 调用Socket对象的发送方法发送数据包// public void send(DatagramPacket p)ds.send(dp);// 释放资源ds.close();} catch (SocketException e) {e.printStackTrace();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}// 获得主机地址private String getip() {WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);DhcpInfo info = wifiManager.getDhcpInfo();return intToIp(info.serverAddress);}//ip格式化private String intToIp(int i) {return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)+ "." + ((i >> 24) & 0xFF);}@Overridepublic void onBackPressed() {super.onBackPressed();}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.research_button:startActivityForResult(new Intent(this, CaptureActivity.class), 0);break;}}
/**
*下面是进行二维码扫描返回的数据
*/@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) {Bundle bundle = data.getExtras();String result = bundle.getString("result");//当拿到结果String[] split = result.split("-");String name = split[0];String psd = split[1];AccessPoint accessPoint = new AccessPoint(name, AccessPoint.SECURITY_WPA2_PSK);isSuccess = wifiLib.connectToAccessPoint(accessPoint,psd);Log.i("HCY", isSuccess ? "连接热点成功" : "连接热点失败");//三木运算符if (isSuccess) {textIsConnect.setText("正在尝试连接");new Thread(runnable).start();//开启了wifi然后开启发送udp广播,当对方接收到了广播就会回播一条数据告诉我已经成功连接} else {textIsConnect.setText("连接热点失败");}wifiLib.stopScan();//连接成功停止扫描}}
}
创建热点
/*
开启热点,并且接受文件页面*/
public class received_activity extends Activity implements View.OnClickListener {private WifiLib wifiLib;private ImageView imageView;private TextView info;private String ip;private WhewView whewView;HorizontalProgressBarWithNumber progressBar;FrameLayout frameLayout;LinearLayout linearLayout;TextView connect_name;ListView list_con;private File fileDirectory;private File[] listFile;List<file_item> list = new ArrayList<>();private myadapter myadapter;private float leng;private ImageView code_image;//二维码展示private RelativeLayout relative_rece;//水波纹界面private Button receive_zx;//扫码发送boolean isfirst = false;@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.receive_zx:if (!isfirst) {receive_zx.setText("等待连接");Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.lw);Bitmap bitamp = EncodingUtils.createQRCode("My_kuaichuan-12345678", 300, 300, bitmap);code_image.setImageBitmap(bitamp);code_image.setVisibility(View.VISIBLE);relative_rece.setVisibility(View.GONE);isfirst = true;} else {receive_zx.setText("扫码连接");code_image.setVisibility(View.GONE);relative_rece.setVisibility(View.VISIBLE);isfirst = false;}break;}}private void assignViews() {receive_zx = (Button) findViewById(R.id.receive_zx);receive_zx.setOnClickListener(this);relative_rece = (RelativeLayout) findViewById(R.id.relative_rece);code_image = (ImageView) findViewById(R.id.code_image);list_con = (ListView) findViewById(R.id.list_con);connect_name = (TextView) findViewById(R.id.connect_name);linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);frameLayout = (FrameLayout) findViewById(R.id.framelayout);progressBar = (HorizontalProgressBarWithNumber) findViewById(R.id.connect_pb);View view = findViewById(R.id.title);TextView textView = (TextView) view.findViewById(R.id.title_tv);Button button = (Button) view.findViewById(R.id.back_button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {tuichu();}});whewView = (WhewView) findViewById(R.id.whewview);textView.setText("接收文件");info = (TextView) findViewById(R.id.info);imageView = (ImageView) findViewById(R.id.imageView);}//初始化数据/*** 退出*/public void tuichu() {android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);builder.setTitle("提示");builder.setIcon(R.drawable.lw);builder.setMessage("是否关闭热点并退出??");builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {wifiLib.closeWifiAp();stopService(new Intent(received_activity.this, Receive_service.class));//关闭接收服务finish();}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create();builder.show();}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.received_activity);getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);assignViews();//初始化数据setWifi();//开启热点whewView.start();//开启水波纹咻一咻的效果new Thread(new Runnable() {@Overridepublic void run() {receive_udp();}}).start();//开启udp接收者接收udp,如果连接上了就能接收到list_con.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {int length = listFile.length;fileDirectory = listFile[length - position - 1];openFile(fileDirectory);}});list_con.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {AlertDialog.Builder builder = new AlertDialog.Builder(received_activity.this);builder.setTitle("提示");builder.setIcon(R.drawable.lw);builder.setMessage("确定删除??");builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {File file = listFile[position];file.delete();show_file_list(fileDirectory);}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(received_activity.this, "点击了取消", Toast.LENGTH_SHORT).show();}});builder.create();builder.show();return true;}});}//查找当前文件路径的子文件夹,并显示在listview列表上public void show_file_list(File file) {//判断当前文件目录下是否有子文件if (file.isDirectory()) {listFile = file.listFiles();// 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件if (list.size() > 0) {list.clear();}for (int i = 0; i < listFile.length; i++) {file_item item = new file_item();//实例化对象if (listFile[i].isDirectory()) {//是文件时设置图标item.setDrawable_int(R.drawable.ll);} else {String name = listFile[i].getName();if (name.indexOf(".") == -1) {item.setDrawable_int(R.drawable.le);} else {String[] names = name.split("\\.");if (names[1].equals("txt")) {item.setDrawable_int(R.drawable.m_);} else if (names[1].equals("zip")) {item.setDrawable_int(R.drawable.me);} else if (names[1].equals("jpg")) {item.setDrawable_int(R.drawable.lq);} else if (names[1].equals("mp4")) {item.setDrawable_int(R.drawable.mv);} else if (names[1].equals("mp3")) {item.setDrawable_int(R.drawable.lo);} else {item.setDrawable_int(R.drawable.le);}}}item.setFile_name(listFile[i].getName());list.add(0, item);}if (myadapter == null) {myadapter = new myadapter(list, this);list_con.setAdapter(myadapter);} else {myadapter.notifyDataSetChanged();}} else {}}/*** 打开文件** @param file*/private void openFile(File file) {Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置intent的Action属性intent.setAction(Intent.ACTION_VIEW);//获取文件file的MIME类型String type = getMIMEType(file);//设置intent的data和Type属性。intent.setDataAndType(/*uri*/Uri.fromFile(file), type);//跳转startActivity(intent);}/*** 根据文件后缀名获得对应的MIME类型。** @param file*/private String getMIMEType(File file) {String type = "*/*";String fName = file.getName();//获取后缀名前的分隔符"."在fName中的位置。int dotIndex = fName.lastIndexOf(".");if (dotIndex < 0) {return type;}/* 获取文件的后缀名 */String end = fName.substring(dotIndex, fName.length()).toLowerCase();if (end == "") return type;//在MIME和文件类型的匹配表中找到对应的MIME类型。for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问,这个MIME_MapTable是什么?if (end.equals(MIME_MapTable[i][0]))type = MIME_MapTable[i][1];}return type;}/*** 数组*/private final String[][] MIME_MapTable = {//{后缀名,MIME类型}{".3gp", "video/3gpp"},{".apk", "application/vnd.android.package-archive"},{".asf", "video/x-ms-asf"},{".avi", "video/x-msvideo"},{".bin", "application/octet-stream"},{".bmp", "image/bmp"},{".c", "text/plain"},{".class", "application/octet-stream"},{".conf", "text/plain"},{".cpp", "text/plain"},{".doc", "application/msword"},{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},{".xls", "application/vnd.ms-excel"},{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{".exe", "application/octet-stream"},{".gif", "image/gif"},{".gtar", "application/x-gtar"},{".gz", "application/x-gzip"},{".h", "text/plain"},{".htm", "text/html"},{".html", "text/html"},{".jar", "application/java-archive"},{".java", "text/plain"},{".jpeg", "image/jpeg"},{".jpg", "image/jpeg"},{".js", "application/x-javascript"},{".log", "text/plain"},{".m3u", "audio/x-mpegurl"},{".m4a", "audio/mp4a-latm"},{".m4b", "audio/mp4a-latm"},{".m4p", "audio/mp4a-latm"},{".m4u", "video/vnd.mpegurl"},{".m4v", "video/x-m4v"},{".mov", "video/quicktime"},{".mp2", "audio/x-mpeg"},{".mp3", "audio/x-mpeg"},{".mp4", "video/mp4"},{".mpc", "application/vnd.mpohun.certificate"},{".mpe", "video/mpeg"},{".mpeg", "video/mpeg"},{".mpg", "video/mpeg"},{".mpg4", "video/mp4"},{".mpga", "audio/mpeg"},{".msg", "application/vnd.ms-outlook"},{".ogg", "audio/ogg"},{".pdf", "application/pdf"},{".png", "image/png"},{".pps", "application/vnd.ms-powerpoint"},{".ppt", "application/vnd.ms-powerpoint"},{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},{".prop", "text/plain"},{".rc", "text/plain"},{".rmvb", "audio/x-pn-realaudio"},{".rtf", "application/rtf"},{".sh", "text/plain"},{".tar", "application/x-tar"},{".tgz", "application/x-compressed"},{".txt", "text/plain"},{".wav", "audio/x-wav"},{".wma", "audio/x-ms-wma"},{".wmv", "audio/x-ms-wmv"},{".wps", "application/vnd.ms-works"},{".xml", "text/plain"},{".z", "application/x-compress"},{".zip", "application/x-zip-compressed"},{"", "*/*"}};/*** 开启热点*/public void setWifi() {WifiLibInitializer.init(this);wifiLib = WifiLib.getInstance();wifiLib.closeWifi();wifiLib.createAccessPoint(WifiApManager.WifiApType.TYPE_WPA_PSK, "My_kuaichuan", "12345678");}@Overridepublic void onBackPressed() {tuichu();}Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if (msg.what == 1) {info.setText("连接成功,等待发送文件");code_image.setVisibility(View.GONE);relative_rece.setVisibility(View.VISIBLE);startService(new Intent(received_activity.this, Receive_service.class));//连接成功开启服务接收数据注册广播接收数据更新发过来的实时进度条MyRceiver1 myRceiver1 = new MyRceiver1();IntentFilter filter1 = new IntentFilter();filter1.addAction("com.rec.leng");//数据总长度received_activity.this.registerReceiver(myRceiver1, filter1);MyRceiver2 myRceiver2 = new MyRceiver2();IntentFilter filter2 = new IntentFilter();filter2.addAction("com.rec.total");//数据实时进度received_activity.this.registerReceiver(myRceiver2, filter2);whewView.stop();//动画停止whewView.setVisibility(View.GONE);new Thread(runnable).start();//接收成功就回传udp通知发送端可以发送了}}};boolean flag = true;Runnable runnable = new Runnable() {@Overridepublic void run() {while (flag) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}sendudp(ip, "11111");}}};//public void sendudp(String ip, String text) {// 创建发送端Socket对象// DatagramSocket()DatagramSocket ds = null;try {ds = new DatagramSocket();// 创建数据,并把数据打包// DatagramPacket(byte[] buf, int length, InetAddress address, int port)// 创建数据byte[] bys = text.getBytes();// 长度int length = bys.length;// IP地址对象InetAddress address = InetAddress.getByName(ip);// 端口int port = 54321;DatagramPacket dp = new DatagramPacket(bys, length, address, port);// 调用Socket对象的发送方法发送数据包// public void send(DatagramPacket p)ds.send(dp);// 释放资源ds.close();} catch (SocketException e) {e.printStackTrace();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//发送udp广播通知已经接收到了广播public void receive_udp() {// 创建接收端的Socket对象DatagramSocket ds = null;boolean flag = true;try {ds = new DatagramSocket(10086);while (flag) {// 创建一个包裹byte[] bys = new byte[1024];DatagramPacket dp = new DatagramPacket(bys, bys.length);// 接收数据ds.receive(dp);// 解析数据ip = dp.getAddress().getHostAddress();String received_udpdate = new String(dp.getData(), 0, dp.getLength());System.out.println(received_udpdate);if (received_udpdate.equals("1")) {Message message = new Message();message.what = 1;handler.sendMessage(message);flag = false;}System.out.println("from " + ip + " data is : " + received_udpdate);}// 释放资源// 接收端应该一直开着等待接收数据,是不需要关闭ds.close();} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//接收发送过来的广播public static String getPrintSize(long size) {size = size / 1024 / 1024;size = size * 100;return String.valueOf((size / 100)) + "."+ String.valueOf((size % 100)) + "-MB";}//字节转换//广播1接收数据的长度public class MyRceiver1 extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {flag = false;frameLayout.setVisibility(View.GONE);linearLayout.setVisibility(View.VISIBLE);String state = Environment.getExternalStorageState();if (state.equals(Environment.MEDIA_MOUNTED)) {//获取shanchuanw文件夹目录fileDirectory = Environment.getExternalStorageDirectory();fileDirectory = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "shanchuan");show_file_list(fileDirectory);}Bundle extras = intent.getExtras();leng = extras.getInt("leng");String fileName = extras.getString("fileName");connect_name.setText(fileName);progressBar.setMax((int) leng);//接收节省的流量SharedPreferences pref = getSharedPreferences("judge",MODE_PRIVATE);float receivesize = pref.getLong("receivesize", 0);float rece_size = receivesize + leng;SharedPreferences.Editor editor = getSharedPreferences("judge",MODE_PRIVATE).edit();editor.putLong("receivesize", (long) rece_size);editor.commit();}}//广播2接收不停发送过来的实时进度public class MyRceiver2 extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Bundle extras = intent.getExtras();float total = extras.getInt("total");progressBar.setProgress((int) total);if (total == leng) {
// myadapter.notifyDataSetChanged();progressBar.setProgress(0);String state = Environment.getExternalStorageState();if (state.equals(Environment.MEDIA_MOUNTED)) {//获取shanchuanw文件夹目录fileDirectory = Environment.getExternalStorageDirectory();fileDirectory = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "shanchuan");show_file_list(fileDirectory);}}}}class myadapter extends BaseAdapter {List<file_item> list;ViewHolder viewHolder;private LayoutInflater mLayoutInflater;public myadapter(List<file_item> list, Context context) {this.list = list;mLayoutInflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {viewHolder = new ViewHolder();convertView = mLayoutInflater.inflate(R.layout.frag1_file, null);//填充view对象viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView);convertView.setTag(viewHolder);} else {viewHolder = (ViewHolder) convertView.getTag();}file_item item = list.get(position);viewHolder.textView.setText(item.getFile_name());viewHolder.imageView.setImageResource(item.getDrawable_int());return convertView;}public class ViewHolder {ImageView imageView;TextView textView;}}}
好了,看到这里,我们的两台手机已经连接成功了,接下来就可以传输文件了
2.数据的传输
我们先看下发送代码
/*** Created by Administrator on 2016/7/6.*/
public class connect_tools {public final static int PORT_NUMBER=9999;//端口号/*** 发送文件* @param context 上下文* @param fileName 文件名* @param path 文件地址* @param ipAddress ip地址* @param length* @param progress* @return*/synchronized public static String SendFile(Context context,String fileName, String path, String ipAddress, int length, ProgressDialog progress ) {int finished = 0;try {Socket name = new Socket(ipAddress, PORT_NUMBER);OutputStream outputName = name.getOutputStream();OutputStreamWriter outputWriter = new OutputStreamWriter(outputName);BufferedWriter bwName = new BufferedWriter(outputWriter);bwName.write(fileName + "x" + length);bwName.close();outputWriter.close();outputName.close();name.close();Socket data = new Socket(ipAddress, PORT_NUMBER);OutputStream outputData = data.getOutputStream();FileInputStream fileInput = new FileInputStream(path);int size;byte[] buffer = new byte[4028];while ((size = fileInput.read(buffer)) != -1) {outputData.write(buffer, 0, size);finished = finished + size;Log.e("upload", finished + "");if (finished < length) {progress.setProgress(finished/1024/1024);} else {progress.dismiss();}}outputData.close();fileInput.close();data.close();SharedPreferences pref = context.getSharedPreferences("judge",context.MODE_PRIVATE);long sendsize = pref.getLong("sendsize",length);long rece_size=sendsize+length;SharedPreferences.Editor editor = context.getSharedPreferences("judge",context.MODE_PRIVATE).edit();editor.putLong("sendsize",rece_size);editor.commit();return fileName + "发送完成";} catch (UnknownHostException e) {progress.dismiss();e.printStackTrace();return "连接已断开,传输失败,请重新连接!";} catch (FileNotFoundException e) {progress.dismiss();e.printStackTrace();return "文件读取失败,请重新尝试!";} catch (IOException e) {progress.dismiss();e.printStackTrace();return "传输失败,请重新尝试!";}}//得到ip地址public static String getip(Activity activity) {WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);DhcpInfo info = wifiManager.getDhcpInfo();return intToIp(info.serverAddress);}
//格式化ip地址private static String intToIp(int i) {return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)+ "." + ((i >> 24) & 0xFF);}
}
调用代码
/*开启线程发送文件fileDirectory.getName()是得到文件名fileDirectory.getPath()是得到文件地址connect_tools.getip(getActivity())得到ip地址fileInputStream.available()流progress是progressdialog*/Runnable runnable = new Runnable() {@Overridepublic void run() {try {String response = connect_tools.SendFile(getContext(), fileDirectory.getName(),fileDirectory.getPath(),connect_tools.getip(getActivity()),fileInputStream.available(), progress);} catch (IOException e) {e.printStackTrace();System.out.println(e.toString());}}};
好了下面是接收代码我是开了一个intentservice来接收,每次只能接收一个文件,这是一个很大的不足我也没有仔细修改
public class Receive_service extends Service {private String fileName;private int leng;public Receive_service() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic void onCreate() {super.onCreate();received();}private void received() {Thread listener = new Thread(new Runnable() {@Overridepublic void run() {while (true) {//绑定端口int port = connect_tools.PORT_NUMBER;try {ServerSocket server = new ServerSocket(port);String response = ReceiveFile(server);System.out.println("" + response);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}});listener.start();}//tcp接收synchronized public String ReceiveFile(ServerSocket server) {int total = 0;try {//接收文件名Socket name = server.accept();InputStream nameStream = name.getInputStream();InputStreamReader streamReader = new InputStreamReader(nameStream);BufferedReader br = new BufferedReader(streamReader);String fileInformation = br.readLine();leng = Integer.parseInt(fileInformation.substring(fileInformation.lastIndexOf("x") + 1));fileName = fileInformation.substring(0, fileInformation.lastIndexOf("x"));Intent intent=new Intent();intent.putExtra("leng",leng);intent.putExtra("fileName",fileName);intent.setAction("com.rec.leng");sendBroadcast(intent);//总进度广播br.close();streamReader.close();nameStream.close();name.close();//接收文件数据Socket data = server.accept();InputStream dataStream = data.getInputStream();String savePath = myPath() + "/" + fileName;FileOutputStream file = new FileOutputStream(savePath, false);byte[] buffer = new byte[1024 * 1024];//文件缓存区大小int size = -1;while ((size = dataStream.read(buffer)) != -1) {file.write(buffer, 0, size);total = total + size;Log.e("get", total + "");Intent intent1=new Intent();intent1.putExtra("total",total);intent1.setAction("com.rec.total");sendBroadcast(intent1);//实时进度发送广播}file.close();dataStream.close();data.close();return fileName + " 接收完成";} catch (Exception e) {return "连接已断开,传输失败,请重新连接!";}}private String myPath() {File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "shanchuan");if (!file.exists())file.mkdir();return Environment.getExternalStorageDirectory().getPath() + "/" + "shanchuan";}
}
做到这里,我们接受的文件就已经完成了
本人原创wifi传输有许多不足的地方,希望大家提出来
下面是我的wifi传输的源码
http://download.csdn.net/detail/z957250254/9608354
如果大家觉得积分有点多 也可以加我qq交流957250254
或者打击一起进入我们的学习群 570047049
这里不仅仅只有安卓,还有懂各种语言、硬件的朋友。