2013-07-30 131 views
2

我需要接受數據使用在後臺服務線程中的ServerSocket ServerSocket在設備[Galaxy s3 19300,Android 4.1。 2]處於WAKE狀態。 但是,當設備處於睡眠模式時,即ServerSocket似乎不能接受,即當屏幕關閉時。ServerSocket在Android不接受睡眠模式[屏幕關閉]

我嘗試使用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(); 
} 
// ------------------------------------------------------------------------- 
+0

您需要發佈服務代碼 - 的問題可能是,手機已經睡覺,所以你從來沒有獲得鎖 –

回答

0

確保您有android.permission.WAKE_LOCK權限和用戶設置他們的無線設置,以「永不眠」在Android的WiFi管理。

我已驗證ServerSocket作品與關閉屏幕在Android 4.0的在標準線程(由活動發起) - 我還沒有嘗試過作爲後臺服務。我能夠從外部服務器向我的電話發送命令,每10分鐘

爲獲取WiFi和電源鎖,這是兩個代碼段需要

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

相關問題