miércoles, 13 de agosto de 2014

Android: Network task

NetworkTask

package ar.com.fennoma.asi.tasks;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import ar.com.fennoma.asi.R;

/**
 * The downside of this class is that you have to override non-traditional
 * methods rather than overriding: onPreExecute, onPostExecute, and
 * doInBackground.
 */
public abstract class NetworkTask<Params, Progress, Result> extends
        AsyncTask<Params, Progress, TaskResult> {

    public interface ICallBack<Result> {

        public void onError(Result result);

        public void onSuccessful(Result result);
    }

    private ICallBack<TaskResult> callback;
    protected Context context;

    public NetworkTask(Context context, ICallBack<TaskResult> callback) {

        this.context = context;
        this.callback = callback;
    }

    // We won't let extending classes to override this method to prevent them
    // from not calling the callback
    @Override
    protected final void onPostExecute(TaskResult response) {

        if (callback != null) {

            if (response.error) {

                callback.onError(response);

            } else {

                callback.onSuccessful(response);
            }
        }

        onPostProcessing(response);
    }

    protected void onPostProcessing(TaskResult response) {
    }

    // We won't let extending classes to override this method to prevent them
    // from skipping the check
    @Override
    protected final TaskResult doInBackground(final Params... params) {

        try {

            if (context == null) {

                throw new IllegalArgumentException("Context cannot be null");
            }

            if (deviceHasAnActiveConnection()) {

                return this.doOnActiveConnection(params);

            } else {

                doOnNoActiveConnection(params);

                return createNoConnectionResult();
            }

        } catch (final Exception e) {

            doOnException(e, params);

            return createExceptionResult(e);
        }
    }

    private TaskResult createNoConnectionResult() {

        TaskResult taskResult = new TaskResult();
        taskResult.error = true;
        taskResult.exception = false;
        taskResult.message = context.getString(R.string.no_connection);

        return taskResult;
    }

    private TaskResult createExceptionResult(Exception e) {

        TaskResult taskResult = new TaskResult();
        taskResult.error = true;
        taskResult.exception = true;
        taskResult.message = context.getString(R.string.exception);

        return taskResult;
    }

    private boolean deviceHasAnActiveConnection() {

        ConnectivityManager systemService = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = systemService.getActiveNetworkInfo();

        return (activeNetworkInfo != null) && activeNetworkInfo.isConnected()
                && activeNetworkInfo.isAvailable();
    }

    protected abstract TaskResult doOnActiveConnection(Params... params) throws Exception;

    // Hook methods
    /**
     * The callback will be called on "onPostExecute" so there is no need to do
     * it in here.
     * 
     * @param params
     */
    protected void doOnNoActiveConnection(Params... params) {

    }

    /**
     * The callback will be called on "onPostExecute" so there is no need to do
     * it in here.
     * 
     * @param params
     */
    protected void doOnException(Exception e, Params... params) {

    }
}

You will need to add the following permission to the manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

No hay comentarios:

Publicar un comentario