Issue
I have an app that needs to do an intensive database operation on start up. The app holds a local copy of the contacts on the phone and synchronizes with the android contact database on startup.
If a user starts the app, an Async Task is started that does the database synch in the background. If the user closes the app, the operation continues running which is fine. However if the user opens the app again, the Async Task is started and an error is produced.
Is there anyway of checking if the Task is already running from a different instance of the app?
Solution
I think you should check the concept of Application
in Android
.
http://developer.android.com/reference/android/app/Application.html
In fact there is no such thing as
different instance of the app
. The Application
is always the same for all your Activities/Services.
That means that you'd left the Activity
and opened it again, 2 cases are possible:
- The system already killed your application. In this case
AsyncTask
is dead already and it's safe to start a new one - The
Application
was still alive, soAsyncTask
possibly still running.
In 2nd case I will recommend to use some static variables, pointing to this AsyncTask
or it's state. If your app was still alive when 2nd time opened - all static references will be still valid, so you can successfully operate.
PS: By the way, in current approach be aware that your application can be terminated by the system at any time. So AsyncTask
can be interrupted in any moment. It it's not ok for you - please check IntentServices
- components, specially designed for background-operation purpose. http://developer.android.com/reference/android/app/IntentService.html
Good luck!
Answered By - AlexN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.