[英]PARTIAL_WAKE_LOCK and thread running in a service
我有一個運行線程的服務。 線程將一些數據保存在文件中(在SD卡中)。 當Android進入睡眠狀態時,我需要服務和線程繼續運行。 我用PARTIAL_WAKE_LOCK嘗試了它,但它不起作用; Android正在休眠時線程停止。 像FULL_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;
}
}
}
}
}
好吧,我會回答我的問題。 我的代碼還可以。 我幾分鍾前發現,問題是在Eken M009S平板電腦(中國平板電腦)中實施PowerManager,這是我進行測試的設備。 在其他設備中,例如在三星的手機中,PARTIAL_WAKE_LOCK非常有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.