Example usage for android.os AsyncTask cancel

List of usage examples for android.os AsyncTask cancel

Introduction

In this page you can find the example usage for android.os AsyncTask cancel.

Prototype

public final boolean cancel(boolean mayInterruptIfRunning) 

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:com.rodrigopontes.androidbubbles.BubblesManager.java

private void cancelAsyncTasks(AsyncTask... animations) {
    for (AsyncTask animation : animations) {
        if (animation != null && !animation.getStatus().name().equals("FINISHED")) {
            animation.cancel(true);
        }/*from   w  ww.  j a  va  2 s .c  om*/
    }
}

From source file:se.chalmers.watchme.activity.MovieDetailsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie_details);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    db = new DatabaseAdapter(getContentResolver());

    this.movie = (Movie) getIntent().getSerializableExtra(MOVIE_EXTRA);
    this.imdb = new IMDBHandler();

    this.poster = (ImageView) findViewById(R.id.poster);
    this.poster.setOnClickListener(new OnPosterClickListener());

    this.imdbButton = (Button) findViewById(R.id.browser_button);
    this.imdbButton.setEnabled(false);

    this.tagField = (EditText) findViewById(R.id.tag_field_details);
    this.noteField = (EditText) findViewById(R.id.note_field_details);

    this.myRatingBar = (RatingBar) findViewById(R.id.my_rating_bar);
    this.myRatingBar.setEnabled(false); // Unable to do this in XML (?)

    this.dialog = new ImageDialog(this);

    // Hide the progress spinner on init
    findViewById(R.id.imdb_loading_spinner).setVisibility(View.INVISIBLE);

    /*/*from w  ww  .  j  av a  2  s  .  co m*/
    * Create a new image download task for the poster image
    */
    this.imageTask = new ImageDownloadTask(new ImageDownloadTask.TaskActions() {

        public void onFinished(Bitmap image) {
            if (image != null) {
                poster.setImageBitmap(image);
            }
        }
    });

    /*
     * If no movie id was received earlier then finish this activity before
     * anything else is done
     */
    if (this.movie == null) {
        // TODO Why does this cause a crash?
        finish();
    }

    // Kick off the fetch for IMDb info IF there's a set API id
    // set.
    if (this.movie.hasApiIDSet()) {
        final AsyncTask<Integer, Void, JSONObject> t = new IMDBTask()
                .execute(new Integer[] { this.movie.getApiID() });

        // Cancel the task after a timeout
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            public void run() {
                if (t.getStatus() == AsyncTask.Status.RUNNING) {
                    t.cancel(true);
                    System.err.println("Fetching IMDb info did timeout");
                }
            }
        }, IMDB_FETCH_TIMEOUT);
    }

    // Populate various view fields from the Movie object
    populateFieldsFromMovie(this.movie);

}

From source file:org.xwiki.android.authenticator.auth.AuthenticatorActivity.java

public void showProgress(CharSequence message, final AsyncTask asyncTask) {
    // To avoid repeatedly create
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        return;//from www .ja v a 2s.  c o  m
    }
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage(message);
    dialog.setIndeterminate(true);
    dialog.setCancelable(true);
    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            Log.i(TAG, "user cancelling authentication");
            if (asyncTask != null) {
                asyncTask.cancel(true);
            }
        }
    });
    // We save off the progress dialog in a field so that we can dismiss
    // it later.
    mProgressDialog = dialog;
    mProgressDialog.show();
}

From source file:com.zenithed.core.widget.scaledimageview.ScaledImageView.java

/**
 * Cancels any running tasks related to the view's images.
 *///from   w ww  . j  ava2  s  . co m
public void cancelAll() {
    AsyncTask.Status status;

    for (AsyncTask task : mTasks) {
        status = task.getStatus();
        if (status == AsyncTask.Status.PENDING || status == AsyncTask.Status.RUNNING)
            task.cancel(true);
    }

    mTasks.clear();
}

From source file:com.oxplot.contactphotosync.AssignContactPhotoActivity.java

@Override
protected void onPause() {

    // XXX experimentally, we're gonna disable contacts sync so it doesn't
    // interfere with our evil root plans - and here we restore it
    // Account a = new Account(account, ACCOUNT_TYPE);
    // ContentResolver.setSyncAutomatically(a, CONTACTS_AUTHORITY,
    // contactsSyncAuto);
    // ContentResolver.setSyncAutomatically(a, CONTACT_PHOTO_AUTHORITY,
    // contactPhotoSyncAuto);

    thumbMemCache.clear();//from w w w.  j a  v a 2 s  .co m
    if (contactsLoader != null)
        contactsLoader.cancel(false);
    for (AsyncTask<?, ?, ?> lt : asyncTasks)
        lt.cancel(false);
    asyncTasks.clear();
    super.onPause();
}

From source file:com.osama.cryptofm.tasks.MyProgressDialog.java

MyProgressDialog(Context context, String title, final AsyncTask task) {
    dialog = new Dialog(context);
    Log.d("dialog", "MyProgressDialog: not cancelable");
    dialog.setCanceledOnTouchOutside(false);
    this.mContext = context;
    this.mContentTitle = title;
    this.isInNotificationMode = false;
    dialog.setContentView(R.layout.task_progress_layout);
    ((TextView) dialog.findViewById(R.id.progress_dialog_title)).setText(title);
    mProgressTextView = ((TextView) dialog.findViewById(R.id.filename_progress_textview));
    mProgressBar = (ProgressBar) dialog.findViewById(R.id.dialog_progressbar);
    mProgressBar.setMax(100);//from  www  . j a  va  2 s  .c om
    dialog.findViewById(R.id.runin_background_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
            buildNotification();
        }
    });
    dialog.findViewById(R.id.cancel_background_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("cancel", "Canceling the task");
            SharedData.IS_TASK_CANCELED = true;
            task.cancel(true);
            dialog.dismiss();

        }
    });
}

From source file:info.icefilms.icestream.browse.BrowseFragment.java

private void ShowProgressDialog(final AsyncTask<?, ?, ?> task) {
    synchronized (mProgressDialogShowing) {
        // Save the passed task
        mProgressDialogTask = task;/*from w  w w  . java 2s  .c om*/

        // Show the progress dialog
        mProgressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.browse_progress), true,
                true, new OnCancelListener() {
                    public void onCancel(DialogInterface dialog) {
                        synchronized (mProgressDialogShowing) {
                            // Cancel the task
                            task.cancel(true);

                            // Signal that the progress dialog will not longer be
                            //    showing
                            mProgressDialogShowing = false;
                        }
                    }
                });
        mProgressDialogShowing = true;
    }
}

From source file:com.example.android.foodrecipes.app.RecipeDetailsFragment.java

private void removeCurrentRecipeFromFavorites() {
    String title = getActivity().getString(R.string.text_please_wait);
    String text = getActivity().getString(R.string.text_removing_from_favorites);

    final ProgressDialog dialog = ProgressDialog.show(getActivity(), title, text);
    dialog.show();/* w  ww .  j  a  v  a 2 s  . c om*/

    final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            String where = RecipeContract.RecipeEntry.COLUMN_EXTERNAL_ID + "=?";
            String[] selectionArgs = new String[] { String.valueOf(mRecipe.getExternalId()) };
            getActivity().getContentResolver().delete(CONTENT_URI, where, selectionArgs);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(getActivity(), getActivity().getString(R.string.recipe_removed_from_favorites),
                    Toast.LENGTH_SHORT).show();

            if (!mTwoPane) {
                // if we operate in the two pane mode we should not finish the activity as
                // we have only one activity, but with two fragments inside
                getActivity().finish();
            }
        }
    };

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                task.cancel(true);
                dialog.dismiss();
            }
            return true;
        }
    });

    task.execute();
}

From source file:im.vector.fragments.PeopleFragment.java

/**
 * Get the known contacts list, sort it by presence and give it to adapter
 *///from w ww.jav a  2 s  .  co m
private void initKnownContacts() {
    final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            // do not sort anymore the full known participants list
            // as they are not displayed unfiltered
            // it saves a lot of times
            // eg with about 17000 items
            // sort requires about 2 seconds
            // sort a 1000 items subset during a search requires about 75ms
            mKnownContacts.clear();
            mKnownContacts.addAll(new ArrayList<>(VectorUtils.listKnownParticipants(mSession).values()));
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            mAdapter.setKnownContacts(mKnownContacts);
        }
    };

    try {
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } catch (final Exception e) {
        Log.e(LOG_TAG, "## initKnownContacts() failed " + e.getMessage());
        asyncTask.cancel(true);

        (new android.os.Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
            @Override
            public void run() {
                initKnownContacts();
            }
        }, 1000);
    }
}

From source file:com.example.android.foodrecipes.app.RecipeDetailsFragment.java

private void saveCurrentRecipeInFavorites() {
    String title = getActivity().getString(R.string.text_please_wait);
    String text = getActivity().getString(R.string.text_saving_in_favorites);

    final ProgressDialog dialog = ProgressDialog.show(getActivity(), title, text);
    final BitmapDrawable bitmapDrawable = (BitmapDrawable) mRecipeImage.getDrawable();

    dialog.show();//  w ww . j  a v a2s. co m

    final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_EXTERNAL_ID, mRecipe.getExternalId());
            cv.put(COLUMN_TITLE, mRecipe.getTitle());
            cv.put(COLUMN_IMAGE_URL, mRecipe.getImageUrl());
            cv.put(COLUMN_SOCIAL_RANK, mRecipe.getSocialRank());
            cv.put(COLUMN_SOURCE_URL, mRecipe.getSourceUrl());
            cv.put(COLUMN_INGREDIENTS, buildIngredientsString(mRecipe.getIngredients()));

            if (PrefsUtil.shouldSaveRecipeImages(getActivity())) {
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    cv.put(COLUMN_IMAGE_CONTENT, stream.toByteArray());
                }
            }

            getActivity().getContentResolver().insert(CONTENT_URI, cv);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(getActivity(), getActivity().getString(R.string.recipe_saved_in_favorites),
                    Toast.LENGTH_SHORT).show();

            mFavoritesActionButton.setEnabled(false);
        }
    };

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                task.cancel(true);
                dialog.dismiss();
            }
            return true;
        }
    });

    task.execute();
}