Example usage for android.os AsyncTask THREAD_POOL_EXECUTOR

List of usage examples for android.os AsyncTask THREAD_POOL_EXECUTOR

Introduction

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

Prototype

Executor THREAD_POOL_EXECUTOR

To view the source code for android.os AsyncTask THREAD_POOL_EXECUTOR.

Click Source Link

Document

An Executor that can be used to execute tasks in parallel.

Usage

From source file:com.example.mahendran.moviecritic.DetailFragment.java

private void makeFavorite() {

    new AsyncTask<Void, Void, Void>() {

        @Override//from  w  ww.  ja v  a 2 s  .  c o m
        protected Void doInBackground(Void... params) {
            if (!isFavorite()) {

                ContentValues movieValues = new ContentValues();
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, mMovie.getId());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_TITLE, mMovie.getTitle());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_POSTER, mMovie.getPoster());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_OVERVIEW, mMovie.getOverview());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_RATED, mMovie.getRating());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_RELEASE, mMovie.getReleaseDate());
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_BACKDROP, mMovie.getBackdrop());
                movieValues.put(MovieContract.MovieEntry.SORT_INFORMATION, "Favorites");
                getContext().getContentResolver().insert(MovieContract.MovieEntry.CONTENT_URI, movieValues

                );
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Toast.makeText(getActivity(), mMovie.getTitle() + " Added to Favorite", Toast.LENGTH_LONG).show();

        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.android.settings.users.EditUserPhotoController.java

private void onPhotoCropped(final Uri data, final boolean cropped) {
    new AsyncTask<Void, Void, Bitmap>() {
        @Override/*w  w w.  j av  a 2 s  .com*/
        protected Bitmap doInBackground(Void... params) {
            if (cropped) {
                InputStream imageStream = null;
                try {
                    imageStream = mContext.getContentResolver().openInputStream(data);
                    return BitmapFactory.decodeStream(imageStream);
                } catch (FileNotFoundException fe) {
                    Log.w(TAG, "Cannot find image file", fe);
                    return null;
                } finally {
                    if (imageStream != null) {
                        try {
                            imageStream.close();
                        } catch (IOException ioe) {
                            Log.w(TAG, "Cannot close image stream", ioe);
                        }
                    }
                }
            } else {
                // Scale and crop to a square aspect ratio
                Bitmap croppedImage = Bitmap.createBitmap(mPhotoSize, mPhotoSize, Config.ARGB_8888);
                Canvas canvas = new Canvas(croppedImage);
                Bitmap fullImage = null;
                try {
                    InputStream imageStream = mContext.getContentResolver().openInputStream(data);
                    fullImage = BitmapFactory.decodeStream(imageStream);
                } catch (FileNotFoundException fe) {
                    return null;
                }
                if (fullImage != null) {
                    final int squareSize = Math.min(fullImage.getWidth(), fullImage.getHeight());
                    final int left = (fullImage.getWidth() - squareSize) / 2;
                    final int top = (fullImage.getHeight() - squareSize) / 2;
                    Rect rectSource = new Rect(left, top, left + squareSize, top + squareSize);
                    Rect rectDest = new Rect(0, 0, mPhotoSize, mPhotoSize);
                    Paint paint = new Paint();
                    canvas.drawBitmap(fullImage, rectSource, rectDest, paint);
                    return croppedImage;
                } else {
                    // Bah! Got nothin.
                    return null;
                }
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mNewUserPhotoBitmap = bitmap;
                mNewUserPhotoDrawable = CircleFramedDrawable.getInstance(mImageView.getContext(),
                        mNewUserPhotoBitmap);
                mImageView.setImageDrawable(mNewUserPhotoDrawable);
            }
            new File(mContext.getCacheDir(), TAKE_PICTURE_FILE_NAME).delete();
            new File(mContext.getCacheDir(), CROP_PICTURE_FILE_NAME).delete();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}

From source file:com.example.amit.tellymoviebuzzz.ImdbFragment.java

private void updateImdb() {

    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");
    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");
    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");
    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");
    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");
    Log.d("Forecast Fragment", "Heljdfkdhfdkfhfkhf");

    FetchImdbThisYearDetails movieTask = new FetchImdbThisYearDetails(getActivity());
    String movie = "thisyear";
    //Utility.getPreferredMovie(getActivity());
    //  movieTask.execute(movie);
    movieTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, movie);
}

From source file:com.pcinpact.ListeArticlesActivity.java

@SuppressLint("NewApi")
@Override/*w  w w. j a v a2 s  . co m*/
public void downloadHTMLFini(String uneURL, ArrayList<Item> desItems) {
    // Si c'est un refresh gnral
    if (uneURL.equals(Constantes.NEXT_INPACT_URL)) {
        for (Item unItem : desItems) {
            // Je l'enregistre en mmoire
            mesArticles.add((ArticleItem) unItem);

            // Je lance le tlchargement de sa miniature
            AsyncImageDownloader monAID = new AsyncImageDownloader(getApplicationContext(), this,
                    Constantes.IMAGE_MINIATURE_ARTICLE, ((ArticleItem) unItem).getURLIllustration());
            // Paralllisation des tlchargements pour l'ensemble de l'application
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                monAID.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            } else {
                monAID.execute();
            }
            nouveauChargementGUI();

            // Je lance le tlchargement de son contenu
            AsyncHTMLDownloader monAHD = new AsyncHTMLDownloader(getApplicationContext(), this,
                    Constantes.HTML_ARTICLE, ((ArticleItem) unItem).getURL(), monDAO);
            // Paralllisation des tlchargements pour l'ensemble de l'application
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                monAHD.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            } else {
                monAHD.execute();
            }
            nouveauChargementGUI();
        }

        // Prfrences de l'utilisateur
        SharedPreferences mesPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        // Nombre d'articles  conserver
        int maLimite = Integer.parseInt(mesPrefs.getString(getString(R.string.idOptionNbArticles),
                getString(R.string.defautOptionNbArticles)));

        // Je limie  n articles (cf prfrence de l'utilisateur)
        for (int i = 0; i < (mesArticles.size() - maLimite); i++) {
            mesArticles.remove(i);
        }
        // DEBUG
        if (Constantes.DEBUG) {
            Log.w("ListeArticlesActivity",
                    "downloadHTMLFini : " + mesArticles.size() + " articles laisss en mmoire");
        }
    }

    // gestion du tlchargement GUI
    finChargementGUI();
}

From source file:fr.cph.chicago.core.fragment.FavoritesFragment.java

/**
 * Start refresh task/*from  w  ww  .j ava2 s .c om*/
 */
private void startRefreshTask() {
    refreshTimingTask = (RefreshTimingTask) new RefreshTimingTask()
            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    favoritesAdapter.refreshUpdatedView();
}

From source file:org.chromium.chrome.browser.physicalweb.UrlManager.java

private void initSharedPreferences() {
    // Check the version.
    final SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    if (prefs.getInt(PREFS_VERSION_KEY, 0) != PREFS_VERSION) {
        new AsyncTask<Void, Void, Void>() {
            @Override/*from  w  w w.ja  v  a  2  s  .c  o m*/
            protected Void doInBackground(Void... params) {
                prefs.edit().putInt(PREFS_VERSION_KEY, PREFS_VERSION)
                        // This clean up code can be deleted in m57.
                        .remove("physicalweb_resolved_urls").apply();
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return;
    }

    // Read the cache.
    mNearbyUrls.addAll(prefs.getStringSet(PREFS_NEARBY_URLS_KEY, new HashSet<String>()));
    for (String serializedUrl : prefs.getStringSet(PREFS_ALL_URLS_KEY, new HashSet<String>())) {
        try {
            JSONObject jsonObject = new JSONObject(serializedUrl);
            UrlInfo urlInfo = UrlInfo.jsonDeserialize(jsonObject);
            mUrlInfoMap.put(urlInfo.getUrl(), urlInfo);
            mUrlsSortedByTimestamp.add(urlInfo.getUrl());
        } catch (JSONException e) {
            Log.e(TAG, "Could not deserialize UrlInfo", e);
        }
    }
    for (String serializedPwsResult : prefs.getStringSet(PREFS_PWS_RESULTS_KEY, new HashSet<String>())) {
        try {
            JSONObject jsonObject = new JSONObject(serializedPwsResult);
            PwsResult pwsResult = PwsResult.jsonDeserialize(jsonObject);
            mPwsResultMap.put(pwsResult.requestUrl, pwsResult);
        } catch (JSONException e) {
            Log.e(TAG, "Could not deserialize PwsResult", e);
        }
    }
    garbageCollect();
}

From source file:org.openbmap.soapclient.ExportSessionTask.java

private void uploadAllWifis(ArrayList<String> wifiFiles) {
    for (int i = 0; i < wifiFiles.size(); i++) {
        while (mActiveUploads >= allowedThreads()) {
            Log.i(TAG, "Maximum number of upload threads reached. Waiting..");
            try {
                Thread.sleep(50);
            } catch (final InterruptedException e) {
            }/*from   w w w  . j a va 2s.  c  om*/
        }
        publishProgress(mAppContext.getResources().getString(R.string.please_stay_patient),
                mAppContext.getResources().getString(R.string.uploading_wifis) + "("
                        + mAppContext.getString(R.string.files) + ": " + String.valueOf(wifiFiles.size() - i)
                        + ")",
                50);
        // enforce parallel execution on HONEYCOMB
        if (!mAnonymousUpload) {
            new AsyncUploader(this, mUser, mPassword, WIFI_WEBSERVICE)
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, wifiFiles.get(i));
            mActiveUploads += 1;
        } else if (mAnonymousUpload && (mToken != null)) {
            new AsyncUploader(this, mToken, WIFI_ANONYMOUS_WEBSERVICE)
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, wifiFiles.get(i));
            mActiveUploads += 1;
        } else {
            Log.e(TAG, "Neither user name nor token was available");
        }
    }
}

From source file:com.dmitrymalkovich.android.popularmoviesapp.details.MovieDetailFragment.java

private void updateFavoriteButtons() {
    // Needed to avoid "skip frames".
    new AsyncTask<Void, Void, Boolean>() {

        @Override/*from w ww  . j  ava2 s .c om*/
        protected Boolean doInBackground(Void... params) {
            return isFavorite();
        }

        @Override
        protected void onPostExecute(Boolean isFavorite) {
            if (isFavorite) {
                mButtonRemoveFromFavorites.setVisibility(View.VISIBLE);
                mButtonMarkAsFavorite.setVisibility(View.GONE);
            } else {
                mButtonMarkAsFavorite.setVisibility(View.VISIBLE);
                mButtonRemoveFromFavorites.setVisibility(View.GONE);
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    mButtonMarkAsFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            markAsFavorite();
        }
    });

    mButtonWatchTrailer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mTrailerListAdapter.getItemCount() > 0) {
                watch(mTrailerListAdapter.getTrailers().get(0), 0);
            }
        }
    });

    mButtonRemoveFromFavorites.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            removeFromFavorites();
        }
    });
}

From source file:com.example.android.hawifi.MainActivity.java

public boolean throwCmd(String command) {
    final Charset asciiCs = Charset.forName("US-ASCII");
    long nonce = myTime();
    String HMAC_PASS = "password";
    String HMAC_KEY = "key";
    //String beforeHmac = "The quick brown fox jumps over the lazy dog";
    String beforeHmac = "/" + HMAC_PASS + "/" + command + "/" + nonce + "/";
    String result = "";
    try {/*from   w  ww  .  j  a  va  2 s. c o m*/
        final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(HMAC_KEY).array(),
                "HmacSHA256");
        sha256_HMAC.init(secret_key);
        final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode(beforeHmac).array());
        for (final byte element : mac_data) {
            result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
        }
    } catch (Exception e) {
        if (D)
            Log.e(TAG, "Crypto Exception");
    }

    DownloadTask dt;
    String url = null;
    if (((RadioButton) findViewById(R.id.radioButton0)).isChecked())
        url = myUrls[0].url;
    else if (((RadioButton) findViewById(R.id.radioButton1)).isChecked())
        url = myUrls[1].url;
    else if (((RadioButton) findViewById(R.id.radioButton2)).isChecked())
        url = myUrls[2].url;
    else if (((RadioButton) findViewById(R.id.radioButton3)).isChecked())
        url = myUrls[3].url;
    else if (((RadioButton) findViewById(R.id.radioButton4)).isChecked())
        url = myUrls[4].url;
    if (url != null) {
        //new DownloadTask().execute(url + command + "/" + nonce + "/" + result);
        dt = new DownloadTask();
        dt.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url + command + "/" + nonce + "/" + result);
    }
    Log.e(TAG, url + command);
    return true;
}

From source file:org.matrix.matrixandroidsdk.db.ConsoleMediasCache.java

/**
 * Load a bitmap from an url./*from  w ww .  j  a v  a  2  s .  c  o m*/
 * The imageView image is updated when the bitmap is loaded or downloaded.
 * The width/height parameters are optional. If they are > 0, download a thumbnail.
 * @param context the context
 * @param imageView the imageView to fill when the image is downloaded
 * @param url the image url
 * @param width the expected image width
 * @param height the expected image height
 * @param rotationAngle the rotation angle (degrees)
 * @return a download identifier if the image is not cached
 */
public static String loadBitmap(Context context, ImageView imageView, String url, int width, int height,
        int rotationAngle) {
    if (null == url) {
        return null;
    }

    // request invalid bitmap size
    if ((0 == width) || (0 == height)) {
        return null;
    }

    String downloadableUrl = downloadableUrl(context, url, width, height);

    if (null != imageView) {
        imageView.setTag(downloadableUrl);
    }

    // check if the bitmap is already cached
    Bitmap bitmap = BitmapWorkerTask.bitmapForURL(context.getApplicationContext(), downloadableUrl,
            rotationAngle);

    if (null != bitmap) {
        if (null != imageView) {
            // display it
            imageView.setImageBitmap(bitmap);
        }
        downloadableUrl = null;
    } else {
        BitmapWorkerTask currentTask = BitmapWorkerTask.bitmapWorkerTaskForUrl(downloadableUrl);

        if (null != currentTask) {
            if (null != imageView) {
                currentTask.addImageView(imageView);
            }
        } else {
            // download it in background
            BitmapWorkerTask task = new BitmapWorkerTask(context, downloadableUrl, rotationAngle);

            if (null != imageView) {
                task.addImageView(imageView);
            }
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
        }
    }

    return downloadableUrl;
}