How to check if Async Task is already running

后端 未结 4 528
一个人的身影
一个人的身影 2020-12-30 19:52

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

4条回答
  •  醉梦人生
    2020-12-30 20:35

    I've managed to handle this problem with some sort of Singleton pattern. Hope it helps.

    // fill the places database from a JSON object
    public class myAsyncTask extends AsyncTask {
    
        Activity mContext = null;
        static AsyncTask myAsyncTaskInstance = null; 
    
        // Private Constructor: can't be called from outside this class
        private myAsyncTask(Activity iContext) {
            mContext = iContext; 
        }
    
        public static AsyncTask getInstance(Activity iContext) {
            // if the current async task is already running, return null: no new async task 
            // shall be created if an instance is already running
            if (myAsyncTaskInstance != null && myAsyncTaskInstance.getStatus() == Status.RUNNING) {
                // it can be running but cancelled, in that case, return a new instance
                if (myAsyncTaskInstance.isCancelled()) {
                    myAsyncTaskInstance = new myAsyncTask(iContext);
                } else {
                    // display a toast to say "try later"
                    Toast.makeText(iContext, "A task is already running, try later", Toast.LENGTH_SHORT).show();    
    
                    return null;
                }
            }
    
            //if the current async task is pending, it can be executed return this instance
            if (myAsyncTaskInstance != null && myAsyncTaskInstance.getStatus() == Status.PENDING) {
                return myAsyncTaskInstance;
            }
    
            //if the current async task is finished, it can't be executed another time, so return a new instance
            if (myAsyncTaskInstance != null && myAsyncTaskInstance.getStatus() == Status.FINISHED) {
                myAsyncTaskInstance = new myAsyncTask(iContext);
            }
    
    
            // if the current async task is null, create a new instance
            if (myAsyncTaskInstance == null) {
                myAsyncTaskInstance = new myAsyncTask(iContext);
            }
            // return the current instance
            return myAsyncTaskInstance;
        }
    
        @Override
        protected Integer doInBackground(Void... iUnUsed) {
            // ...
        }
    }
    

提交回复
热议问题