vuhung3990
12/13/2015 - 9:17 PM

Template using asynctask loader

Template using asynctask loader

package com.example.hungvu.testpack;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;

/**
 * Template Custom Asynctask Loader
 */

// TODO: Edit name and Return Object
public class CustomAsyntaskLoader extends AsyncTaskLoader<Object> {

    private String TAG = "";
    private boolean mCancel;

    /**
     * Constructor
     *
     * @param context Loaders may be used across multiple Activities (assuming they aren't
     *                bound to the LoaderManager), so NEVER hold a reference to the context
     *                directly. Doing so will cause you to leak an entire Activity's context.
     *                The superclass constructor will store a reference to the Application
     *                Context instead, and can be retrieved with a call to getContext().
     */
    public CustomAsyntaskLoader(Context context) {
        super(context);
        TAG = context.getPackageName();
        Log.d(TAG, "CustomAsyntaskLoader");
    }

    private void CancelByUser(){
        mCancel = true;
    }

    /**
     * Subclasses must implement this to take care of loading their data,
     * as per {@link #startLoading()}.  This is not called by clients directly,
     * but as a result of a call to {@link #startLoading()}.
     */
    @Override
    protected void onStartLoading() {
        super.onStartLoading();

        // bug android support v4 loader
        // load on call getSupportLoaderManager#initLoader
        forceLoad();
        mCancel = false;
    }

    /**
     * Subclasses must implement this to take care of stopping their loader,
     * as per {@link #stopLoading()}.  This is not called by clients directly,
     * but as a result of a call to {@link #stopLoading()}.
     * This will always be called from the process's main thread.
     */
    @Override
    protected void onStopLoading() {
        super.onStopLoading();
    }

    /**
     * Subclasses must implement this to take care of resetting their loader,
     * as per {@link #reset()}.  This is not called by clients directly,
     * but as a result of a call to {@link #reset()}.
     * This will always be called from the process's main thread.
     */
    @Override
    protected void onReset() {
        super.onReset();
    }

    @Override
    public Object loadInBackground() {
        while (!mCancel){
            // TODO: do something, design to stop thread by your-self
        }

        // cancel by user
        if(mCancel) cancelLoad();
        return null;
    }
}