gpt4 book ai didi

android - PARTIAL_WAKE_LOCK 和线程在服务中运行

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:54 30 4
gpt4 key购买 nike

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

不知道是我代码有误,还是我没看懂PARTIAL_WAKE_LOCK。有人可以告诉我为什么我的解决方案不起作用吗?

这是启动服务的主要 Activity 代码的一部分:

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 工作得很好。

关于android - PARTIAL_WAKE_LOCK 和线程在服务中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7360234/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com