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

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

Android平台开发

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

实例介绍

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

【核心代码】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警