设为首页 收藏本站
查看: 988|回复: 0

[经验分享] android wifi hotspot

[复制链接]

尚未签到

发表于 2015-9-30 13:37:56 | 显示全部楼层 |阅读模式
http://www.java2s.com/Open-Source/Android/Network/smartphone-networks/softaptest/mobed/yonsei/Main.java.htm

smartphone networks » softaptest » mobed » yonsei » Main.java

package softaptest.mobed.yonsei;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;



import android.app.Activity;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
Button btn_on, btn_off, btn_other;
public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED";
public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
public static final int WIFI_AP_STATE_DISABLING = 0;
public static final int WIFI_AP_STATE_DISABLED = 1;
public static final int WIFI_AP_STATE_ENABLING = 2;
public static final int WIFI_AP_STATE_ENABLED = 3;
public static final int WIFI_AP_STATE_FAILED = 4;
private String TAG = "Soft AP Test";
private WifiManager mWifiManager;


private TextView serverStatus;
// default ip
public static String SERVERIP = "192.168.43.1";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
private String receiveBuff = "";

//Variables for UCP broadcast
Thread uThread = new Thread(new udpThread());
private static final String REMOTE_KEY = "SSNUDP";
private static final int DISCOVERY_PORT = 9000;
private static final int LISTEN_PORT = 9000;
private static final int TIMEOUT_MS = 15000;
private static final String mChallenge = "Hey, SSN_UDP neighbors, from server";
private String udp_receive_buff = "";


public boolean setWifiApEnabled(boolean enabled)
{
if (enabled)
{ // disable WiFi in any case
mWifiManager.setWifiEnabled(false);
}
try {
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "SSN";
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);   
netConfig.preSharedKey = "comsys505";
Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, netConfig, enabled);
} catch (Exception e) {
Log.e(TAG, "", e);
return false;
}
}
public int getWifiApState() {
try {
Method method = mWifiManager.getClass().getMethod("getWifiApState");
return (Integer) method.invoke(mWifiManager);
} catch (Exception e) {
Log.e(TAG, "", e);
return WIFI_AP_STATE_FAILED;
}
}
public class ServerThread implements Runnable
{
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
receiveBuff = null;
while ((receiveBuff = in.readLine()) != null) {
Log.d("ServerActivity", receiveBuff);
handler.post(new Runnable() {
@Override
public void run()
{
// do whatever you want to the front end
// this is where you can be creative
                                      
serverStatus.setText(receiveBuff);
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}

/*gets the IP address of your phone's network
*This function is used for TCP/IP communication via internet connection
*/
//    private String getLocalIpAddress()
//    {
//        try {
//            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
//                NetworkInterface intf = (NetworkInterface) en.nextElement();
//                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
//                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
//                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
//                }
//            }
//        } catch (SocketException ex) {
//            Log.e("ServerActivity", ex.toString());
//        }
//        return null;
//    }


/*Section for UDP broadcast*/

public class udpThread implements Runnable
{
public void run()
{
try
{
DatagramSocket socket = new DatagramSocket(LISTEN_PORT);
socket.setBroadcast(true);
socket.setSoTimeout(TIMEOUT_MS);
//              socket.setBroadcast(true);
//              
//              sendDiscoveryRequest(socket);
//           
//              Log.d("UDP_Activity", "UDP broadcast Sent");
socket.setBroadcast(true);
sendDiscoveryRequest(socket);
Log.d("UDP_Activity", "UDP broadcast Sent");
listenForResponses(socket);
handler.post(new Runnable() {
@Override
public void run()
{
// do whatever you want to the front end
// this is where you can be creative
                        
serverStatus.setText(udp_receive_buff);
}
});
if(socket.getSoTimeout()>0)
{
Log.d(TAG, "Socket time out, is closing. TIMEOUT_MS: " + TIMEOUT_MS);
socket.close();
}
Log.d("UDP_Activity", "Listen to UDP response");
}
catch (IOException e)
{
Log.e(TAG, "Could not send discovery request", e);
}
}
}

/**
* Send a broadcast UDP packet containing a request for boxee services to
* announce themselves.
*
* @throws IOException
*/
//    private boolean send_broadcast(byte msg[]) {
//      
//      try {
//        
//        int port = 9000;
//        
//        DatagramSocket socket = new DatagramSocket(port);
//        
//        InetAddress group = InetAddress.getByName("192.168.143.255"); //get_broadcast_address();   
//        
//        Log.i(TAG, "Address: " + group.toString());
//        
//        socket.setBroadcast(true);
//        
//        DatagramPacket packet = new DatagramPacket(msg, msg.length, null, port);
//        
//        socket.send(packet);
//        
//      }
//      catch (Exception e) {
//        Log.e("Broadcast", "error: " + e.getMessage());
//        return false;
//      }
//      
//      
//      return true;
//    }
private void sendDiscoveryRequest(DatagramSocket socket) throws IOException
{
String data = String
.format(
"<bdp1 cmd=\"discover\" application=\"iphone_remote\" challenge=\"%s\" signature=\"%s\"/>",
mChallenge, getSignature(mChallenge));
Log.d(TAG, "Sending data " + data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
}
/**
* Calculate the broadcast IP we need to send the packet along. If we send it
* to 255.255.255.255, it never gets sent. I guess this has something to do
* with the mobile network not wanting to do broadcast.
* @throws UnknownHostException
*/
private InetAddress getBroadcastAddress() throws UnknownHostException
{
DhcpInfo dhcp = mWifiManager.getDhcpInfo();
if (dhcp == null)
{
Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
//functions to calculate broadcastAddress from the current address
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}

/**
* Listen on socket for responses, timing out after TIMEOUT_MS
*
* @param socket
*          socket on which the announcement request was sent
* @throws IOException
*/
private void listenForResponses(DatagramSocket socket) throws IOException
{
byte[] buf = new byte[1024];
try
{
while (true)
{
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
udp_receive_buff = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received response " + udp_receive_buff);
}
}
catch (SocketTimeoutException e)
{
Log.d(TAG, "Receive timed out");
}
}


/**
* Calculate the signature we need to send with the request. It is a string
* containing the hex md5sum of the challenge and REMOTE_KEY.
*
* @return signature string
*/
private String getSignature(String challenge)
{
MessageDigest digest;
byte[] md5sum = null;
try
{
digest = java.security.MessageDigest.getInstance("MD5");
digest.update(challenge.getBytes());
digest.update(REMOTE_KEY.getBytes());
md5sum = digest.digest();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
StringBuffer hexString = new StringBuffer();
for (int k = 0; k < md5sum.length; ++k)
{
String s = Integer.toHexString((int) md5sum[k] & 0xFF);
if (s.length() == 1)
hexString.append('0');
hexString.append(s);
}
return hexString.toString();
}







/*Section for TCP/IP communication client part*/
public class ClientThread implements Runnable
{
public void run()
{
boolean connected;
try
{
String serverIp="192.168.43.224";
InetAddress serverAddr = InetAddress.getByName(serverIp);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
//                socket.setSoTimeout(TCP_TIMEOUT_MS);
connected = true;
while (connected)
{
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
}
catch (Exception e)
{
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
}
catch (Exception e)
{
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
btn_on = (Button) findViewById(R.id.ButtonOn);
btn_off = (Button) findViewById(R.id.ButtonOff);
btn_other = (Button) findViewById(R.id.ButtonOther);
udp_receive_buff = "";
btn_on.setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
setWifiApEnabled(true);
}
});   
btn_off.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
setWifiApEnabled(false);
}
});  
btn_other.setOnClickListener
(
new OnClickListener() {
public void onClick(View v) {
uThread.stop();
uThread.start();

//                    String hello = "Hello world!";
//                    
//                    if (send_broadcast(hello.getBytes()))
//                      Log.i("Broadcast", "Everything is good!");
              
}
}
);

serverStatus = (TextView) findViewById(R.id.serverStatus);
//        SERVERIP = getLocalIpAddress();

//This part is for TCP/IP communication
//        Thread fst = new Thread(new ServerThread());
//        fst.start();
        
}


@Override
protected void onStop()
{
uThread.stop();
super.onStop();
}
@Override
public void onDestroy()
{
uThread.stop();
super.onDestroy();
}


}
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-120992-1-1.html 上篇帖子: PC使用网线上网的条件下,通过PC的Wifi共享提供手机上网教程 下篇帖子: 【智能家居篇】wifi网络访问原理(下一个)——联想Association
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表