2020年10月1日 星期四

xamarin: enable & receive UDP broadcast (Android 11 嘛會通哦)

 AndroidManifest.xml

----------------------------------

...

...

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

-----------------------------------

in android app Activity c# :

---------------------------------

          var wifiManager = (WifiManager)GetSystemService(Context.WifiService);

            MulticastLock mLock = wifiManager.CreateMulticastLock("lock");

            mLock.Acquire();

            using (var udpClient = new UdpClient(你要聆聽的port number)) {

                var asyncResult = udpClient.BeginReceive(null, null);

                var timeToWait = TimeSpan.FromSeconds(30);//30秒,超過就結束

                asyncResult.AsyncWaitHandle.WaitOne(timeToWait);

                if (asyncResult.IsCompleted) {

                    IPEndPoint remoteEP = null;

                    byte[] receivedData = udpClient.EndReceive(asyncResult, ref remoteEP);

                    string msg = System.Text.Encoding.UTF8.GetString(receivedData);

                    Console.WriteLine($"get end point message:{msg}");

                    mLock.Release();

                } else {

                    mLock.Release(); 

                    Console.WriteLine("UDP failed!!!!!!");

                }

            }

--------------------------------

參考 : 這裡

以上,希望對你有幫助


沒有留言:

張貼留言