I have a service that starts a thread. The stream saves some data in a file (in the SD card). When Android goes to sleep, I need the service and thread to continue to work. I tried it with PARTIAL_WAKE_LOCK, but it does not work; the thread terminates while Android is sleeping. Other locks, such as FULL_WAKE_LOCK, work, but I need to use PARTIAL_WAKE_LOCK, because in the future in this thread I will read from the serial port, and I do not care that the screen turns off.
I do not know if I have a mistake in the code, or if I do not understand PARTIAL_WAKE_LOCK. Can anyone tell me why my solution is not working?
This is part of the main action code in which the service is deprecated:
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)); } }
This is the service code:
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; } } } } }
source share