android - 提交清除中断状态

标签 android multithreading sharedpreferences interrupt

在我正在开发的应用程序中,我有一个循环运行的线程。在循环内,评估多个条件,并根据这些条件,将一个或另一个值存储在 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/

相关文章:

android - React Native API 实现导致错误

android - 如何计算RecyclerView的滚动速度

android - SASLError 使用 PLAIN : not-authorized

android - Mobilock 应用程序在 BOOT_COMPLETED 广播之前启动......这怎么可能?

C++ : Passing threadID to function anomaly

java - 这段代码有竞争条件吗?

multithreading - 服务结构锁定和超时

android - Android 上的 SQLite 和 SharedPreferences 文件的安全性如何?

Android - 在设备上存储图像?

android - 为什么虽然允许备份应用程序,但重新安装应用程序有时会清除 SP?