Return to Snippet

Revision: 41942
at February 25, 2011 03:28 by BenClayton


Initial Code
public class MyThins {
	
	private Object[] itemsToProcess;
	private OnProgressListener<FilesNeedDownloadingCheckerTask> onProgressListener;
	private OnFinishedListener<FilesNeedDownloadingCheckerTask, Result> onFinishedListener;
	private FilesNeedDownloadingCheckerTask task;
	
	public void setOnProgressListener(OnProgressListener<FilesNeedDownloadingCheckerTask> onProgressListener) {
		this.onProgressListener = onProgressListener;
	}
	
	public void setOnFinishedListener(OnFinishedListener<FilesNeedDownloadingCheckerTask, Result> onFinishedListener) {
		this.onFinishedListener = onFinishedListener;
	}
	
	public FilesNeedDownloadingChecker(Object[] items) {
		super();
		this.itemsToProcess = items;
	}
	
	public void cancel() {
		if (task != null) {
			task.cancel(true);
		}
	}
	
	public void runAsync() {
		task = new MyThingTask();
		task.execute(null);
	}
	
	public class Result {
		public ArrayList<Object> results = new ArrayList<Object>();
	}
	
	public class MyThingTask extends AsyncTask<Object, Integer, Result> {
                Result result = new Result();

		@Override
		protected Result doInBackground(Object... params) {
                        // do things with this.itemsToProcess..
                        if (isCancelled()) { return null);
                        //	
			
			return result;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			
			if (onProgressListener != null) {
				onProgressListener.onProgress(this, (double)values[0] / (double) remoteFiles.length );
			}
		}
		
		@Override
		protected void onPostExecute(Result result) {
			super.onPostExecute(result);
			
			if (onFinishedListener != null) {
				onFinishedListener.onFinished(this, result);
			}
		}
	}
}

Initial URL

                                

Initial Description

                                

Initial Title
Android: Template for an AsyncTask (task to run in a background thread)

Initial Tags

                                

Initial Language
Java