android中的ServerSocket在SLEEP MODE上不接受[屏幕关闭]

时间:2013-07-30 07:37:47

标签: android serversocket wakelock wifimanager android-wake-lock

我需要使用ServerSocket接受数据,该服务器位于后台服务中的线程中 当设备[Galaxy s3 19300,Android 4.1.2]处于WAKE状态时,ServerSocket接受数据。 但是当设备处于休眠模式时,即当屏幕关闭时,ServerSocket似乎不接受。

我尝试使用WIFI锁,全部和部分以及POWER锁,但这两个选项都无法使ServerSocket监听。

解决这些问题的任何线索?

代码

// -------------------------------------------------------------------------
private void CallSock() {
    Log.i("$$$$$",
        "Before WiFI State is " + Integer.toString(wm.getWifiState()));
    wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "MyWifiLock");
    PowerManager mgr = (PowerManager) mContext
            .getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyWakeLock");
    wakeLock.acquire();
    if (!wifiLock.isHeld()) {
        wifiLock.acquire();
        Log.i("$$$$$", "Wifi lock acquired");
    }
    Looper.prepare();
    sSocket = new ServerSocket(serverPort);
    while (true) {
        Log.i("$$$$$", "In the While loop WiFI State is "
                + Integer.toString(wm.getWifiState()));
        Rulecontent.writeLogInfo("Waiting to recieve file");
        String fileName = readFile();
    }
}

// -------------------------------------------------------------
public String readFile() {
    StringBuilder x = null;
    try {
        InputStream in = null;
        Socket recvClientSocket = sSocket.accept();
        in = recvClientSocket.getInputStream();
        byte[] bytes = new byte[1024];
        x = new StringBuilder();
        int numRead = 0;
        while ((numRead = in.read(bytes)) >= 0) {
            x.append(new String(bytes, 0, numRead));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return x.toString();
}
// -------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

确保您拥有android.permission.WAKE_LOCK权限,并且用户已在Android Wifi管理器中将其Wifi设置设为“从不睡眠”。

我已经在标准的主题(由活动启动)中验证ServerSocket适用于Android 4.0中的屏幕 - 我还没试过它作为后台服务。我可以从外部服务器每隔10分钟向我的手机发送命令。

用于获取 Wifi和Power 锁定的代码段,都是

https://stackoverflow.com/a/18916511/830775