繁体   English   中英

PARTIAL_WAKE_LOCK和服务中运行的线程

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM