My code works fine and I would like to know if I chose the best strategy to implement my code, or if It can written better (more fast, more clear, best use of design pattern, etc).
In my android application WelcomeActivity
, in the onCreate
method, I start a really simple service that load data from a file:
public class LoadDataService extends IntentService {
private int result;
@Override
protected void onHandleIntent(Intent intent) {
try
{
FileTestSingleton.getInstance(); //this could be long, read from file
result = Activity.RESULT_OK;
} catch (Exception e)
{
Log.e(LoadDataService.class.getName(), "FILE DATA LOADING ERROR \n" + e);
result = Activity.RESULT_CANCELED;
}
publishResults(result);
}
private void publishResults(int result) {
stopSelf();
}
}
Some activity after, the user click a button to go to the next step of my APP. The onCreate
method of MyNewActivity
need the data from the service, otherwise it's ok to freeze the application, because if the data aren't loaded, nothing can be done. For example, I read that to stop the UI thread is a bad thing, but I need to stop it, otherwise my new activity will not have data to show.
So in my onCreate
:
while (FileTestSingleton.getState()==Semaphore.LOADING)
{
Thread.sleep(250);
}
fileTest = FileTestSingleton.getInstance();
Is this a proper way to wait?
Semaphore
is a simple enum
that I created inside the FileTestSingleton
class:
public enum Semaphore
{
EMPTY,
LOADING,
DONE;
}
private static Semaphore semaphore = Semaphore.EMPTY;
private static FileTestSingleton fileTest;
public static FileTestSingleton getInstance() throws Exception
{
if (fileTest==null && semaphore!=Semaphore.LOADING)
{
semaphore = Semaphore.LOADING;
fileTest = new FileTestSingleton(); //read from file, really slow
semaphore = Semaphore.DONE;
}
return fileTest;
}
public static Semaphore getState()
{
return semaphore;
}
Why I think that I can't use AsyncTask
:
The problem is: I load some txt files on the startup in the WelcomeActivity
that is for 2 seconds on the screen. After the app go in the MiddleActivity
and the user in the meantime can choose some options before he starts the final step of the application: FinalActivity
. This FinalActivity
need that all the txt files are loaded in the singleton.