UDP套接字android线程

时间:2014-04-15 07:10:32

标签: android

我创建一个UDP Android客户端,以便在设备在线时自动(使用广播接收器)将其信息(MAC地址)发送到UDP服务器。服务器只打印出设备的MAC地址。但我不知道为什么它会在设备连接到Internet时向服务器发送许多数据包。可能是我的广播接收器或线程中的一些问题。这是我的代码:

NetworkChangeReceiver.java

public class NetworkChangeReceiver extends BroadcastReceiver {
public final static int PORT = 8005;
public final static String SERVER = "163.180.117.182";

DatagramSocket socket;
DatagramPacket recvPacket;
DatagramPacket sendPacket;
@Override
public void onReceive(Context context, Intent intent) {

    if(Utils.isConnectingToInternet(context)==true){
        final Context con = context;
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    //Socket implementation
                    Utils.send(con);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start(); 
        MainActivity.ip.setText(Utils.getIPv4Adress(context));
    }

}

}

Utils.java

public class Utils {
public final static int PORT = 8005 ;
public final static String SERVER ="163.180.117.182";


public static String getMacAddress(Context context) {
    WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    String macAddress = wimanager.getConnectionInfo().getMacAddress();
    if (macAddress == null) {
        macAddress = "Device don't have mac address or wi-fi is disabled";
    }
    return macAddress;
}

public static String getIPv4Adress(Context context){
    WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wimanager.getConnectionInfo().getIpAddress());
    return ip;      
}

// Checking for all possible internet providers
public static boolean isConnectingToInternet(Context context){

    ConnectivityManager connectivity = 
                         (ConnectivityManager) context.getSystemService(
                          Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}

public static void send(Context context){
    try{
        DatagramSocket socket ;
        DatagramPacket recvPacket ;
        DatagramPacket sendPacket ;

        socket = new DatagramSocket() ;

        Log.i(Utils.getMacAddress(context) + ":" + socket.getLocalPort(), "Client Host and port");

        String MAC_Address = Utils.getMacAddress(context);

        sendPacket = new DatagramPacket(MAC_Address.getBytes(), MAC_Address.getBytes().length, InetAddress.getByName(SERVER), PORT) ;

        socket.send(sendPacket);
        socket.close();
        }
        catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

}

MainActivity.java

public class MainActivity extends ActionBarActivity {
Button btn;
public static TextView ip ;
public static TextView mac;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i(Utils.getIPv4Adress(getApplicationContext()), "ip");
    ip = (TextView) findViewById(R.id.ip);
    ip.setText(Utils.getIPv4Adress(getApplicationContext()));

    mac = (TextView) findViewById(R.id.mac);
    mac.setText(Utils.getMacAddress(getApplicationContext()));

    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        //Socket implementation
                        Utils.send(getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start(); 
            // TODO Auto-generated method stub

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

0 个答案:

没有答案