gpt4 book ai didi

android - 提交清除中断状态

转载 作者:行者123 更新时间:2023-11-30 04:08:20 24 4
gpt4 key购买 nike

在我正在开发的应用程序中,我有一个循环运行的线程。在循环内,评估多个条件,并根据这些条件,将一个或另一个值存储在 SharedPreferences 中。

public void run()
{
try
{
SharedPreferences preferences =
context.getSharedPreferences("MyPrefs", Activity.MODE_PRIVATE);

SharedPreferences.Editor editor = preferences.edit();

while (true)
{
if (condition1)
{
editor.putBoolean("mykey", "1");
}
else if (condition 2)
{
editor.putBoolean("mykey", "2");
}
editor.commit();

if (isInterrupted())
throw new InterruptedException();

Thread.sleep(60000); // 60 seconds
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}

该线程在onResume方法中由Activity启动,在onPause方法中被中断。

如果线程在休眠时被 Activity (主线程)中断,则抛出InterruptedException。没关系。

但我的问题是,如果 Activity (主线程)在运行时(而不是休眠)中断线程。 “中断标志”设置为 true,但在编辑器上调用提交后,标志设置为 false,因此我无法中断抛出 InterruptedException 的线程。

我能做什么?

谢谢

最佳答案

我刚遇到同样的问题并找到了解决方案。

您可能会使用 editor.apply()而不是 editor.commit() !

apply() 而不是 commit() 的原因是它在新线程上执行 I/O,因为它不需要等待返回值:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

关于android - 提交清除中断状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11247852/

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