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?
I think you should check the concept of
ApplicationinAndroid.http://developer.android.com/reference/android/app/Application.html
In fact there is no such thing as
. The
Applicationis always the same for all yourActivities/Services.That means that you’d left the
Activityand opened it again, 2 cases are possible:AsyncTaskis dead already and it’s safe to start a new oneApplicationwas still alive, soAsyncTaskpossibly still running.In 2nd case I will recommend to use some static variables, pointing to this
AsyncTaskor 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
AsyncTaskcan be interrupted in any moment. It it’s not ok for you – please checkIntentServices– components, specially designed for background-operation purpose. http://developer.android.com/reference/android/app/IntentService.htmlGood luck!