如何在Android设备上接收UDP广播 [英] How to receive UDP broadcasts on an Android device

查看:1058
本文介绍了如何在Android设备上接收UDP广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使我的Android手机接收UDP广播?

How can I make my Android phone receive UDP broadcasts?

目前,我正在使用平板电脑和手机测试我的应用程序.问题在于,只有平板电脑可以用作服务器,而不能用作电话.

At the moment i am testing my app using a tablet and a phone. The problem is that only the tablet can work as a server, not the phone.

我的应用中出现问题的场景是: -客户端正在本地网络中发送广播 -服务器正在接收此广播,并直接向客户端发送响应

The scenario of my app where the problem is: - Client is sending broadcast in a local network - Server is receiving this broadcast and sending a response to the client directly

我敢肯定,我知道我知道这是怎么回事,因为该应用程序仅在服务器在平板电脑上运行时才起作用,也就是说,手机无法按标准接收广播..如何解决此问题?

I am pretty sure I think I know what's wrong as the app only works when the server is running on the tablet and that is that the phone can't receive broadcasts by standard.. So how do I get around this?

我尝试为服务器实现以下代码以使其接收广播:

I have tried implementing the following code for the server to make it receive broadcasts:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        if (wifi != null){
            Toast.makeText(getApplicationContext(), "WifiLock create!", Toast.LENGTH_LONG).show();
            WifiManager.WifiLock lock = wifi.createWifiLock("mylock");
            lock.acquire();
        }

此外,我在我的应用中具有以下权限:

Also, I have the following permissions in my app:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

有人知道如何解决吗? 预先感谢

Does anyone know how this can be solved? Thanks in advance

推荐答案

默认情况下,Android阻止所有广播的wifi消息以节省电量. 您必须创建一个wifilock对象,并获取该锁以允许广播消息. 请参阅此处以获取更多信息: WIFI锁定

By default Android Block all broadcast wifi messages to save power. You must create a wifilock object and the aquire the lock to allow the broadcast messages. See here for more info: WIFILOCKS

这篇关于如何在Android设备上接收UDP广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆