<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: NanYuanZhiGe</title>
    <description>The latest articles on DEV Community by NanYuanZhiGe (@nanyuanzhige).</description>
    <link>https://dev.to/nanyuanzhige</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2636944%2F2207fafc-bca4-4915-ad2d-cd09acfbb0fd.png</url>
      <title>DEV Community: NanYuanZhiGe</title>
      <link>https://dev.to/nanyuanzhige</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nanyuanzhige"/>
    <language>en</language>
    <item>
      <title>Receive UDP Broadcast from PC on Android</title>
      <dc:creator>NanYuanZhiGe</dc:creator>
      <pubDate>Wed, 01 Jan 2025 12:45:44 +0000</pubDate>
      <link>https://dev.to/nanyuanzhige/receive-udp-broadcast-from-pc-on-android-1if5</link>
      <guid>https://dev.to/nanyuanzhige/receive-udp-broadcast-from-pc-on-android-1if5</guid>
      <description>&lt;p&gt;This article implements how to receive UDP broadcasts from a PC on your mobile phone.&lt;br&gt;
Let's first complete the code implementation on the PC side., which is very simple.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private final ScheduledExecutorService askService= Executors.newSingleThreadScheduledExecutor();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void runWaitConnectThead(){
        askService.scheduleAtFixedRate(this::sendAskMessage, 0, boardCastConfig.getWAIT_MS(), TimeUnit.MILLISECONDS);
    }
protected void sendAskMessage(){
        byte[] message = this.hostName.getBytes();
        try (DatagramSocket datagramSocket = new DatagramSocket()) {
            datagramSocket.setBroadcast(true);
            InetAddress boardcastAddr = InetAddress.getByName("255.255.255.255");
            DatagramPacket datagramPacket = new DatagramPacket(message, message.length, boardcastAddr, 1885);
            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the second code block above, askService will start immediatly(the second param) and will continue to exucute function "sendAskMessage()"， which boardcast UDP packet， every boardCastConfig.getWAIT_MS() milliseconds. In my code, it repeats every 5s.&lt;/p&gt;

&lt;p&gt;Now, you have achieved 50% success.&lt;br&gt;
Before writing our receiving code, we need add some permissions in AndroidMnifest.xml file or your application will not able to run.&lt;br&gt;
Here are the permissions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;uses-permission android:name="android.permission.INTERNET" /&amp;gt;
    &amp;lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&amp;gt;
    &amp;lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/&amp;gt;
    &amp;lt;uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then let's create a service in MainActivity, and implement our receiving code in it. By the way, don't forget adding this service in AndroidManifest.xml file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent waitBoardCastService=new Intent(this, WaitBoardCastService.class);
        startService(waitBoardCastService);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;service android:name=".on_wait.WaitBoardCastService"/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can finish our receiving code. It contains two part.&lt;br&gt;
①create a new thread(I didn't show that in my code, but that's very important, you can't start your application if you left network operation in main thread)&lt;br&gt;
②acquiring multicast lock(this step is extremely important, without this, you can't receive UDP packet)&lt;br&gt;
③receiving UDP packet&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WifiManager wifi =(WifiManager)getSystemService(MyApplication.WIFI_SERVICE);
WifiManager.MulticastLock lock = wifi.createMulticastLock("any_tag");
lock.acquire();
try {
    DatagramSocket socket = new DatagramSocket(1885);
    byte[] receiveData = new byte[1024];
    DatagramPacket receivePacket = new DatagramPacket(receiveData, 
    receiveData.length);
    Log.v("hello","waiting");
    socket.receive(receivePacket);
    String receiveMessage = new String(receivePacket.getData(), 0,receivePacket.getLength());
    Log.v("hello","received!");
    socket.close();
} catch (IOException e) {
    Toast.makeText(MyApplication.getContext(), "NetWork Error",Toast.LENGTH_LONG).show();
} finally {
    lock.release();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;My results:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6b12ko9xawe4rntltjas.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6b12ko9xawe4rntltjas.png" alt="Image description" width="800" height="84"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>android</category>
    </item>
  </channel>
</rss>
