-
-
Save martinbowling/1952000 to your computer and use it in GitHub Desktop.
Android State Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.IO; | |
public class StateManager | |
{ | |
public StateManager () | |
{ | |
} | |
private static Dictionary<string,object> currentState; | |
private static object locker = new object(); | |
private static string stateFile = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "state"); | |
public static object GetObject(string key) | |
{ | |
lock(locker) | |
{ | |
loadState(); | |
if(!currentState.ContainsKey(key)) | |
return null; | |
return currentState[key]; | |
} | |
} | |
public static void SetObject(string key,object value) | |
{ | |
lock(locker) | |
{ | |
loadState(); | |
if(currentState.ContainsKey(key)) | |
currentState[key] = value; | |
else | |
currentState.Add(key,value); | |
} | |
} | |
private static void loadState() | |
{ | |
if(currentState != null) | |
return; | |
if(!File.Exists(stateFile)) | |
{ | |
currentState = new Dictionary<string, object>(); | |
return; | |
} | |
var formatter = new BinaryFormatter(); | |
using(var stream = new FileStream(stateFile,FileMode.Open, FileAccess.Read, FileShare.Read)){ | |
currentState = (Dictionary<string,object>) formatter.Deserialize(stream); | |
stream.Close(); | |
} | |
} | |
private static void saveState() | |
{ | |
var formatter = new BinaryFormatter(); | |
using(var stream = new FileStream(stateFile,FileMode.Create,FileAccess.Write, FileShare.None)) | |
{ | |
formatter.Serialize(stream, currentState); | |
stream.Close(); | |
} | |
} | |
public static void Synchronize() | |
{ | |
lock(locker) | |
{ | |
saveState(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment