UDP sending on Android4.0 and before versions

允我心安 提交于 2019-12-06 10:05:21

Fisrt of all be sure your manifest have the internet permission

"uses-permission android:name="android.permission.INTERNET"

then after SDK8 you must use a thread like this

public class MainActivity extends Activity implements OnClickListener
{
public static final String DEST_IP = "192.168.1.7";
    public static final int DEST_UDP_PORT = 1234;
    public static final byte[] buf = {'H','e','l','l','o',' ','U','D','P'}; 
    public Button Send_UDP_Button;

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

        Send_UDP_Button = (Button)findViewById(R.id.button1); 
        Send_UDP_Button.setOnClickListener(this); 
    }

    @Override
    public void onClick(View v)
    {
        new Thread(new Client()).start();
    }

    public class Client implements Runnable
    { 
        @Override 
        public void run()
        { 
            try
            { 
                InetAddress serverAddr = InetAddress.getByName(DEST_IP); 
                DatagramSocket socket = new DatagramSocket(); 
                DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, DEST_UDP_PORT); 
                socket.send(packet); 
                socket.close(); 
            }
            catch (Exception e)
            { 
                Log.w("Too Bad",e);
            } 
        } 
    } 
}

I hope this will help ! Sorry can't vote up your question I don't have enough reputation ! :-(

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!