In the application I’m developing, I have a thread that is running in a loop. Inside the loop, several conditions are evaluated, and depends on these conditions, a value or another is stored in the 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();
}
}
This thread is started by an Activity in the onResume method, and is interrupted in the onPause method.
If the thread is interrupted by the activity (main thread) when it is sleeping, an InterruptedException is thrown. That is ok.
But my problem is that if the activity (main thread) interrupts the thread when it is running (and not sleeping). The “interrupted flag” is set to true, but after calling commit on the editor, the flag is set to false, so I can’t interrupt the thread throwing an InterruptedException.
What can I do?
Thanks
Calling
editor.commit()is going to do I/O. If there is a pending interrupt on the thread then this will likely abort the I/O and clear the pending interrupt.In order to do what you want you will probably need to prevent that the thread is interrupted while committing. You’ll need to synchronize the access so that the application can only interrupt it while the thread is sleeping. Something like this: