/******************************************************************************* * Copyright (c) 2011 Michel DAVID mimah35-at-gmail.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package fr.gotorennes.util; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.util.Log; import fr.gotorennes.R; public abstract class BackgroundTask<T> { private boolean showPopup; private String message; private AsyncTask<Void,String,T> task; private List<Handler> handlers = new ArrayList<Handler>(); public BackgroundTask() { this(true); } public BackgroundTask(String message) { this(message, true); } public BackgroundTask(boolean showPopup) { this(null, showPopup); } public BackgroundTask(String message, boolean showPopup) { this.message = message; this.showPopup = showPopup; } public void addHandler(Handler handler) { handlers.add(handler); } protected abstract T execute(); protected abstract void callback(T result); public void start(Activity context) { if(message == null) { message = context.getString(R.string.chargement); } final ProgressDialog waitDialog = showPopup ? ProgressDialog.show(context, context.getString(R.string.titre), message, true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if(task != null){ task.cancel(true); } task.cancel(true); } }) : null; task = new AsyncTask<Void, String, T>() { @Override protected T doInBackground(Void... params) { try { return BackgroundTask.this.execute(); } catch(Throwable ex) { Log.e("GoToRennes", ex.getMessage(), ex); } return null; } @Override protected void onPostExecute(T result) { callback(result); if (waitDialog != null) { try { waitDialog.dismiss(); } catch(Exception ex) { //Cas étrange sur certains tel // http://stackoverflow.com/questions/2745061/java-lang-illegalargumentexception-view-not-attached-to-window-manager } } for(Handler handler : handlers) { Message message = new Message(); message.obj = result; handler.dispatchMessage(message); } } }; task.execute(); } }