设备屏幕关闭时,部分唤醒锁定可接收UDP广播数据包

时间:2019-05-22 16:50:20

标签: java android multithreading wakelock

我正在尝试开发一个可接收UDP广播数据包的Android应用,然后将其发布到端点。一个单独的线程继续监听广播数据包。装置萤幕开启时,应用程式运作正常。当设备屏幕关闭时,即使我获得了以下锁,该应用也不会收到这些数据包:PARTIAL_WAKE_LOCK / WifiLock(WIFI_MODE_FULL_HIGH_PERF)/ MulticastLock

public class MainActivity extends AppCompatActivity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        if (wl == null) {
            wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myapp:sampWakeLockTag");
        }
        if (!wl.isHeld()) {
            wl.acquire();
        }
        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiLock == null) {
            wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TAG);
        }
        if (!wifiLock.isHeld()) {
            wifiLock.acquire();
        }
        if (multicastLock == null) {
            multicastLock = wifi.createMulticastLock("multicast_Lock");
        }
        multicastLock.setReferenceCounted(true);
        if (!multicastLock.isHeld()) {
            multicastLock.acquire();
        }

    }

    @Override
    protected void onStart() {
        udpServerThread = new UdpServerThread(UdpServerPORT);
        udpServerThread.start();
        super.onStart();
    }

    private class UdpServerThread extends Thread{

        int serverPort;
        DatagramSocket socket;

        boolean running;

        public UdpServerThread(int serverPort) {
            super();
            this.serverPort = serverPort;
        }

        public void setRunning(boolean running){
            this.running = running;
        }

        @Override
        public void run() {

            running = true;

            try {
                socket = new DatagramSocket(null);
                socket.setBroadcast(true);
                socket.bind(new InetSocketAddress("0.0.0.0",serverPort));
                String[] prevPacket = new String[0];
                while(running){
                    byte[] buf = new byte[256];
                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);     //this code blocks the program flow
                    final String packetText = new String(buf, 0, packet.getLength());
                    jsonPacket.put("packetText", packetText);
                    // POST to endpoint
                }

            }
        }
    }

}

我正在运行Android Oreo的三星平板电脑上对此进行测试。 你们能指导我正确的方向吗?我已经在这个问题上停留了一段时间

0 个答案:

没有答案