|
public class ParameterlessTask extends Task { |
|
|
|
private static final String TAG = ParameterlessTask.class.getSimpleName(); |
|
|
|
protected Callable0 mCallable = null; |
|
protected Action0 mOnBefore = null; |
|
protected Action0 mOnSuccess = null; |
|
protected Action<Throwable> mOnError = null; |
|
protected Action0 mOnAfter = null; |
|
protected long mDelay = 0; |
|
protected Throwable mException = null; |
|
|
|
/** |
|
* Executes task and passes result within specified context. |
|
* @param context |
|
*/ |
|
public void execute(Context context) { |
|
|
|
AsyncTaskCompat.executeParallel( |
|
new AsyncTask<Void, Void, Void>() { |
|
|
|
private Throwable mException = null; |
|
|
|
@Override |
|
protected void onPreExecute() { |
|
if (mOnBefore != null) |
|
mOnBefore.call(); |
|
} |
|
|
|
@Override |
|
protected Void doInBackground(Void... params) { |
|
try { |
|
if (mDelay != 0) { |
|
Thread.sleep(mDelay); |
|
} |
|
mCallable.call(); |
|
return null; |
|
} |
|
catch (Throwable ex) { |
|
Log.e(TAG, "Exception caught: " + ex.toString()); |
|
mException = ex; |
|
return null; |
|
} |
|
} |
|
@Override |
|
protected void onPostExecute(Void result) { |
|
if (context != null) { |
|
if (mException != null) { |
|
if (mOnError != null) |
|
mOnError.call(mException); |
|
if (mOnAfter != null) |
|
mOnAfter.call(); |
|
} |
|
else { |
|
if (mOnSuccess != null) |
|
mOnSuccess.call(); |
|
if (mOnAfter != null) |
|
mOnAfter.call(); |
|
} |
|
} |
|
else { |
|
Log.w(TAG, "Context is null"); |
|
} |
|
} |
|
}); |
|
} |
|
|
|
/** Sets the delay value, in milliseconds, before starting the task. |
|
* @param delay delay value, in milliseconds |
|
* @return |
|
*/ |
|
public ParameterlessTask delayed(long delay) { |
|
mDelay = delay; |
|
return this; |
|
} |
|
|
|
/** |
|
* Sets operation that will be called before execution of the background task |
|
* @param onBefore |
|
* @return |
|
*/ |
|
public ParameterlessTask onBefore(Action0 onBefore) { |
|
mOnBefore = onBefore; |
|
return this; |
|
} |
|
|
|
/** |
|
* Sets operation that will be called when the background task completed successfully |
|
* @param onSuccess |
|
* @return |
|
*/ |
|
public ParameterlessTask onSuccess(Action0 onSuccess) { |
|
mOnSuccess = onSuccess; |
|
return this; |
|
} |
|
|
|
/** |
|
* Sets operation that will be called if exception thrown in the background task |
|
* @param onError |
|
* @return |
|
*/ |
|
public ParameterlessTask onError(Action<Throwable> onError) { |
|
mOnError = onError; |
|
return this; |
|
} |
|
|
|
/** |
|
* Can be called anyway after the background task (after onSuccess or onError) |
|
* @param onAfter |
|
* @return |
|
*/ |
|
public ParameterlessTask onAfter(Action0 onAfter) { |
|
mOnAfter = onAfter; |
|
return this; |
|
} |
|
} |