在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Android平台开发 → android wifi之间数据传输、创建热点 示例源码

android wifi之间数据传输、创建热点 示例源码

Android平台开发

下载此实例
  • 开发语言:Java
  • 实例大小:21.85M
  • 下载次数:30
  • 浏览次数:243
  • 发布时间:2017-10-12
  • 实例类别:Android平台开发
  • 发 布 人:xtich
  • 文件格式:.zip
  • 所需积分:2
 相关标签: wifi 热点 demo

实例介绍

【实例简介】

wifi基本功能

【实例截图】

from clipboard


from clipboard



【核心代码】


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
package com.ethanco.wifitransmit;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
 
 
public class QuickTransferActivity extends Activity implements DisplayMesage, ITransferResult {
    /**
     * Called when the activity is first created.
     */
    TextView content;
    Button mBtn3, mBtn4;
    WifiAdmin mWifiAdmin;
    WifiApAdmin wifiAp;
    Context context;
    final static String TAG = "robin";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        content = (TextView) this.findViewById(R.id.content);
 
        /**
         * 打开的步骤见 http://blog.csdn.net/hudashi/article/details/25283087
         */
        mBtn3 = (Button) findViewById(R.id.button3);
        mBtn4 = (Button) findViewById(R.id.button4);
        mBtn3.setText("点击连接Wifi");
        mBtn4.setText("点击创建Wifi热点");
        context = this;
        mBtn3.setOnClickListener(new Button.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
 
                mWifiAdmin = new WifiAdmin(context) {
 
                    @Override
                    public void myUnregisterReceiver(BroadcastReceiver receiver) {
                        // TODO Auto-generated method stub
                        unregisterReceiver(receiver);
                    }
 
                    @Override
                    public Intent myRegisterReceiver(BroadcastReceiver receiver, IntentFilter filter) {
                        // TODO Auto-generated method stub
                        registerReceiver(receiver, filter);
                        return null;
                    }
 
                    @Override
                    public void onNotifyWifiConnected() {
                        // TODO Auto-generated method stub
                        Log.v(TAG, "have connected success!");
                        Log.v(TAG, "###############################");
                    }
 
                    @Override
                    public void onNotifyWifiConnectFailed() {
                        // TODO Auto-generated method stub
                        Log.v(TAG, "have connected failed!");
                        Log.v(TAG, "###############################");
                    }
 
                };
                mWifiAdmin.openWifi();
                mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo(Constant.HOST_SPOT_SSID, Constant.HOST_SPOT_PASS_WORD,
                        WifiAdmin.TYPE_WPA));
 
            }
        });
 
        mBtn4.setOnClickListener(new Button.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
 
                wifiAp = new WifiApAdmin(context);
                wifiAp.startWifiAp(Constant.HOST_SPOT_SSID, Constant.HOST_SPOT_PASS_WORD);
            }
        });
    }
 
    public void onClick(View view) {
        if (view.getId() == R.id.button1) {
            WifiManager wifiManage = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            DhcpInfo info = wifiManage.getDhcpInfo();
            WifiInfo wifiinfo = wifiManage.getConnectionInfo();
            String ip = intToIp(wifiinfo.getIpAddress());
            String serverAddress = intToIp(info.serverAddress);
            new Sender(serverAddress, this, this).start();
            Log.w("robin", "ip:"   ip   "serverAddress:"   serverAddress   info);
        } else if (view.getId() == R.id.button2) {
            Receiver service = new Receiver(this, this);
            service.start();
 
        }
    }
 
    Handler handler = new Handler();
    StringBuffer strBuffer = new StringBuffer();
 
    public void displayMesage(final String msg) {
        Runnable r = new Runnable() {
 
            public void run() {
                // TODO Auto-generated method stub
                if (strBuffer.length() > 1024) {
                    strBuffer.delete(0, 100);
                }
                strBuffer.append(msg   "\n");
                content.setText(strBuffer.toString());
                content.invalidate();
            }
        };
        handler.post(r);
    }
 
    // 将获取的int转为真正的ip地址,参考的网上的,修改了下
 
    private String intToIp(int i) {
        return (i & 0xFF)   "."   ((i >> 8) & 0xFF)   "."   ((i >> 16) & 0xFF)   "."   ((i >> 24) & 0xFF);
    }
 
    @Override
    public void appendMesage(String msg) {
        displayMesage(msg);
 
    }
 
    @Override
    public void onResult(int result, long size) {
        if (wifiAp != null) {
            wifiAp.closeWifiAp(context);
        }
        // TODO Auto-generated method stub
        closeWifi();
        Runnable r = new Runnable() {
 
            @Override
            public void run() {
                // TODO Auto-generated method stub
                displayMesage("try to open wifi");
                openWifi();
                displayMesage("open wifi end");
            }
 
        };
        handler.postDelayed(r, 30 * 1000);
 
    }
 
    WifiManager mWifiManager;
 
    // 打开WIFI
    public void openWifi() {
        if (mWifiAdmin != null) {
            mWifiAdmin.openWifi();
            return;
        }
        if (mWifiManager == null) {
            mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }
 
    // 关闭WIFI
    public void closeWifi() {
        if (mWifiAdmin != null) {
            mWifiAdmin.closeWifi();
            return;
        }
        if (mWifiManager == null) {
            mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
}
 
interface DisplayMesage {
    void displayMesage(String msg);
 
    void appendMesage(String msg);
}
 
interface ITransferResult {
    void onResult(int result, long size);
}
 
class Receiver extends Thread {
    private static BufferedReader in;
    DisplayMesage console;
    ITransferResult transferResult;
 
    Receiver(DisplayMesage console, ITransferResult transferResult) {
        super();
        this.console = console;
        this.transferResult = transferResult;
 
    }
 
    public void run() {
        try {
            ServerSocket socketService = new ServerSocket(3358);
            Log.i("robin", "waiting a connection from the client"   socketService);
            Socket sock = socketService.accept();
            String hostAddress = sock.getLocalAddress().getHostAddress();
            String inetAddress = sock.getInetAddress().getHostAddress();
 
            Log.w("robin", "local:"   hostAddress   "| inetAddress"   inetAddress   "|"   sock.getRemoteSocketAddress());
            Log.w("robin", "local name:"   sock.getLocalAddress().getHostName()   "| inetAddress"
                      sock.getInetAddress().getHostName()   "|"   InetAddress.getLocalHost().getHostAddress());
            in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String line;
            boolean flag = true;
            long count = 0;
            long time = System.currentTimeMillis();
            do {
                line = in.readLine();
                if (flag) {
                    console.displayMesage("Recevie:"   line);
                    flag = false;
                }
                count = count   line.length();
                if (count % 1024 == 0) {
                    console.displayMesage("Recevied:"   ((count << 1) >> 10)   "kB data");
                }
            } while (!Constant.END.equals(line));
            Log.w("robin", "you input is :"   line);
            long t = System.currentTimeMillis() - time;
            if (t == 0)
                t = 1;
            count = count << 1;
            long rate = ((count / t) * 1000) / 1024;
            count = count >> 10;
            console.displayMesage("Recevied:"   count   "kB data"   " in "   t   " ms"   " at rate:"   rate
                      " kB/second");
            Log.i("robin", "exit the app");
            sock.close();
            socketService.close();
            transferResult.onResult(1, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
class Sender extends Thread {
    DisplayMesage console;
    String serverIp;
    ITransferResult transferResult;
 
    Sender(String serverAddress, DisplayMesage console, ITransferResult transferResult) {
        super();
        serverIp = serverAddress;
        this.console = console;
        this.transferResult = transferResult;
    }
 
    public void run() {
        Socket sock = null;
        PrintWriter out;
        try {
 
            // 声明sock,其中参数为服务端的IP地址与自定义端口
            sock = new Socket(serverIp, 3358);
            Log.w("robin", "I am try to writer"   sock);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        char data[] = new char[1024 * 10];
        for (int i = 0; i < data.length; i  ) {
            data[i] = (char) i;
        }
        try {
            if (sock != null) {
                // 声明输出流out,向服务端输出“Output Message!!”
                final String msg = "Hello,this is robin!!";
                Log.w("robin", "try to writer");
                out = new PrintWriter(sock.getOutputStream(), true);
                StringBuffer strBuffer = new StringBuffer();
                strBuffer.append(msg);
                String str = msg;
                for (int i = 0; i < 1024; i  ) {
                    if (i != 0) {
                        str = msg   System.currentTimeMillis()   "|";
                        out.write(data);
                    }
 
                    out.println(str);
                    Log.w("robin", str);
                    if (i == 0) {
                        console.displayMesage("send message....");
                    } else if (i % 100 == 0) {
                        console.displayMesage("send message "   i   " success!");
                    }
                    if (strBuffer.length() > 1024) {
                        strBuffer.delete(0, strBuffer.length());
                    }
                }
                out.println(Constant.END);
                out.flush();
            }
            transferResult.onResult(1, 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}



标签: wifi 热点 demo

实例下载地址

android wifi之间数据传输、创建热点 示例源码

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

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

网友评论

发表评论

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

查看所有0条评论>>

小贴士

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

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

关于好例子网

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

;
报警