2011-09-09 79 views
6

我有一個運行線程的服務。該線程將一些數據保存在文件中(在SD卡中)。當Android進入睡眠狀態時,我需要服務和線程繼續運行。我用PARTIAL_WAKE_LOCK嘗試了它,但它不起作用;線程停止,而Android正在睡覺。像FULL_WAKE_LOCK之類的其他鎖定工作,但我需要使用PARTIAL_WAKE_LOCK,因爲將來,在該線程中,我將從串行端口讀取數據,而不關心屏幕關閉。PARTIAL_WAKE_LOCK和線程在服務中運行

我不知道我是否在代碼中出現了一些錯誤,或者我不明白PARTIAL_WAKE_LOCK。有人可以告訴我爲什麼我的解決方案無法解決?

這是主要活動的代碼,其中的服務stareted的一部分:

public void onClick(View v) { 
    if (SerialPortService.WAKELOCK == null) { 
     PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
     SerialPortService.WAKELOCK = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, SerialPortService.WL_TAG); 
     SerialPortService.WAKELOCK.acquire(); 
     startService(new Intent(getApplicationContext(), SerialPortService.class)); 
    } 
} 

這是服務的代碼:

public class SerialPortService extends Service { 

    public static String WL_TAG = "serial_port_wl_tag"; 
    public static PowerManager.WakeLock WAKELOCK = null; 
    private BufferedWriter out = null; 
    private ReadThread readThread; 

    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    public void onCreate() { 
     super.onCreate(); 
     try { 
      File root = Environment.getExternalStorageDirectory(); 
      if (root.canWrite()){ 
       File dataFile = new File(root, "batterytest.txt"); 
       FileWriter dataFileWritter = new FileWriter(dataFile); 
       out = new BufferedWriter(dataFileWritter); 
      } 
     } catch (IOException ioe) { 
      Log.d("TEST", "Could not open file " + ioe.getMessage()); 
     } 
     readThread = new ReadThread(); 
     readThread.start(); 
    } 

    public void onDestroy() { 
     if (readThread != null) readThread.interrupt(); 
     WAKELOCK.release(); 
     WAKELOCK = null; 
     try { 
      out.close(); 
     } catch (IOException ioe) { 
      Log.d("TEST", "Could not close file " + ioe.getMessage()); 
     } 
     super.onDestroy(); 
    } 

    private class ReadThread extends Thread { 
     public void run() { 
      super.run(); 
      while (!isInterrupted()) { 
       try { 
        Thread.sleep(5000); 
        if (out != null) { 
         Calendar now = Calendar.getInstance(); 
         out.write(now.getTime().toString()); 
         out.newLine(); 
       } catch (IOException ioe) { 
        Log.d("TEST", "Could not read file " + ioe.getMessage());} 
        return; 
       } catch (InterruptedException e) { 
        return; 
       } 
      } 
     } 

    } 


} 

回答

9

嗯,我會回答我的問題。我的代碼是好的。我在幾分鐘前發現,問題在於Eken M009S平板電腦(中文平板電腦)中的PowerManager的實現,該平臺是我進行測試的設備。在其他設備中,例如三星的手機,PARTIAL_WAKE_LOCK完美運行。