Tengo un servicio que ejecuta un subproceso. El hilo guarda algunos datos en un archivo (en la tarjeta sd). Cuando Android se va a dormir, necesito que el servicio y el hilo sigan funcionando. Lo intenté con un PARTIAL_WAKE_LOCK, pero no funciona; el hilo se detiene mientras Android está durmiendo. Otros bloqueos como FULL_WAKE_LOCK funcionan, pero necesito usar PARTIAL_WAKE_LOCK porque, en el futuro, en ese hilo lo leeré desde un puerto serie y no me importa que la pantalla se apague.PARTIAL_WAKE_LOCK y ejecución de subprocesos en un servicio
No sé si tengo algún error en el código, o si no entiendo el PARTIAL_WAKE_LOCK. ¿Alguien puede decirme por qué mi solución no funciona?
Esto es parte del código de la actividad principal, donde se stareted el servicio:
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));
}
}
Este es el código del servicio:
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;
}
}
}
}
}