PARTIAL_WAKE_LOCK和服务中运行的线程

时间:2011-09-09 10:22:37

标签: android

我有一个运行线程的服务。线程将一些数据保存在文件中(在SD卡中)。当Android进入睡眠状态时,我需要服务和线程继续运行。我用PARTIAL_WAKE_LOCK尝试了它,但它不起作用; Android正在休眠时线程停止。像FULL_WAKE_LOCK这样的其他锁可以工作,但是我需要使用PARTIAL_WAKE_LOCK,因为将来在该线程中我将从串口读取并且我不关心屏幕是否关闭。

我不知道代码中是否有错误,或者我不理解PARTIAL_WAKE_LOCK。有人可以告诉我为什么我的解决方案不会破坏?

这是主要活动代码的一部分,其中服务已被确定:

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;
                }
            }
        }

    }


}

1 个答案:

答案 0 :(得分:10)

好吧,我会回答我的问题。我的代码还可以。我几分钟前发现,问题是在Eken M009S平板电脑(中国平板电脑)中实施PowerManager,这是我进行测试的设备。在其他设备中,例如在三星的手机中,PARTIAL_WAKE_LOCK可以很好地工作。