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.amit.tellymoviebuzzz.ImdbUpcomingFragment.java

private void updateTmdb() {

    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");

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

From source file:ch.gianulli.flashcards.BoardsFragment.java

@Override
public void onRefresh() {
    if (mBoardLoader != null) {
        mBoardLoader.cancel(true);//from  w w  w.  j a va2s.  co  m
        mBoardLoader = null;
    }

    mBoardLoader = new AsyncTask<Void, Void, ArrayList<Board>>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mAdapter.isEmpty()) {
                setActivePage(Page.PROGRESS);
                mRefreshLayout.setRefreshing(false);
            } else {
                setActivePage(Page.BOARD_LIST);
                mRefreshLayout.setRefreshing(true);
            }
        }

        @Override
        protected ArrayList<Board> doInBackground(Void... params) {
            try {
                // Get boards from Trello
                ArrayList<Board> result = Board.listAllBoards(mTrelloApi);

                // Remove hidden boards
                Set<String> hiddenBoards = mPrefModel.getHiddenBoards();
                for (int i = result.size() - 1; i >= 0; --i) {
                    String id = result.get(i).getId();
                    if (hiddenBoards.contains(id)) {
                        result.remove(i);
                    }
                }

                return result;
            } catch (TrelloNotAuthorizedException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTrelloApi.requestAuthorization(getActivity().getSupportFragmentManager());
                    }
                });
            } catch (TrelloNotAccessibleException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setActivePage(Page.NO_CONNECTION);
                    }
                });
                Log.d("test", "Trello not accessible: " + e.getMessage());
            }

            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<Board> boards) {
            mRefreshLayout.setRefreshing(false);

            mAdapter.setBoards(boards);
            if (boards != null) {
                if (mAdapter.isEmpty()) {
                    setActivePage(Page.NO_BOARDS);
                } else {
                    setActivePage(Page.BOARD_LIST);
                }
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:org.exobel.routerkeygen.ui.Preferences.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    getActionBar().setDisplayHomeAsUpEnabled(true);

    findPreference("download").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            if (isDictionaryServiceRunning()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_download_running),
                        Toast.LENGTH_SHORT).show();
                return true;
            }//from w w w  .  j av a 2  s  .  c  o m
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_no_network), Toast.LENGTH_SHORT)
                        .show();
                return true;
            }

            // Don't complain about dictionary size if user is on a
            // wifi connection
            if ((((WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE))).getConnectionInfo()
                    .getSSID() != null) {
                try {
                    checkCurrentDictionary();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(DIALOG_ASK_DOWNLOAD);
            return true;
        }
    });

    //        boolean app_installed = AdsUtils.checkDonation(this);
    final PreferenceCategory mCategory = (PreferenceCategory) findPreference("2section");
    //        if (!app_installed) {
    //            mCategory.removePreference(findPreference("analytics_enabled"));
    //            // If you haven't the donate app installed remove the paypal donate
    //            // link.
    //            mCategory.removePreference(findPreference("donate_paypal"));
    //            findPreference("donate_playstore").setOnPreferenceClickListener(
    //                    new OnPreferenceClickListener() {
    //                        public boolean onPreferenceClick(Preference preference) {
    //                            try {
    //                                startActivity(new Intent(Intent.ACTION_VIEW,
    //                                        Uri.parse("market://details?id="
    //                                                + GOOGLE_PLAY_DOWNLOADER)));
    //                            } catch (android.content.ActivityNotFoundException anfe) {
    //                                startActivity(new Intent(
    //                                        Intent.ACTION_VIEW,
    //                                        Uri.parse("http://play.google.com/store/apps/details?id="
    //                                                + GOOGLE_PLAY_DOWNLOADER)));
    //                            }
    //                            Toast.makeText(getApplicationContext(),
    //                                    R.string.msg_donation, Toast.LENGTH_LONG)
    //                                    .show();
    //                            return true;
    //                        }
    //                    });
    //        } else {
    //            // If you have the donate app installed no need to link to it.
    //            mCategory.removePreference(findPreference("donate_playstore"));
    //            if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
    //                //Play Store is quite restrictive nowadays
    //                mCategory.removePreference(findPreference("donate_paypal"));
    //            } else {
    //                findPreference("donate_paypal").setOnPreferenceClickListener(
    //                        new OnPreferenceClickListener() {
    //                            public boolean onPreferenceClick(Preference preference) {
    //                                final String donateLink = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V3FFBTRTTV5DN";
    //                                Uri uri = Uri.parse(donateLink);
    //                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
    //
    //                                return true;
    //                            }
    //                        });
    //            }
    //        }
    if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
        mCategory.removePreference(findPreference("update"));
    } else {
        findPreference("update").setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    protected void onPreExecute() {
                        showDialog(DIALOG_WAIT);
                    }

                    protected Void doInBackground(Void... params) {
                        lastVersion = UpdateCheckerService.getLatestVersion();
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                        removeDialog(DIALOG_WAIT);
                        if (isFinishing())
                            return;
                        if (lastVersion == null) {
                            showDialog(DIALOG_ERROR);
                            return;
                        }
                        if (!Preferences.VERSION.equals(lastVersion.version)) {
                            showDialog(DIALOG_UPDATE_NEEDED);
                        } else {
                            Toast.makeText(Preferences.this, R.string.msg_app_updated, Toast.LENGTH_SHORT)
                                    .show();
                        }

                    }
                };
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                    task.execute();
                } else {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
                // Checking for updates every week
                startService(new Intent(getApplicationContext(), UpdateCheckerService.class));
                return true;
            }
        });
    }
    findPreference("changelog").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_CHANGELOG);
            return true;
        }
    });
    findPreference("about").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_ABOUT);
            return true;
        }
    });
    findPreference(dicLocalPref).setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(new Intent(getApplicationContext(), FileChooserActivity.class), 0);
            return true;
        }
    });
    final CheckBoxPreference autoScan = (CheckBoxPreference) findPreference("autoScan");
    autoScan.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            findPreference("autoScanInterval").setEnabled(autoScan.isChecked());
            return true;

        }
    });
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    findPreference("autoScanInterval").setEnabled(
            prefs.getBoolean(Preferences.autoScanPref, getResources().getBoolean(R.bool.autoScanDefault)));
}

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

private void uploadAllCells(ArrayList<String> cellFiles) {
    for (int i = 0; i < cellFiles.size(); i++) {
        // thread control for the poor: spawn only MAX_THREADS tasks
        while (mActiveUploads >= allowedThreads()) {
            Log.i(TAG, "Number of upload threads exceeds max parallel threads (" + mActiveUploads + "/"
                    + allowedThreads() + "). Waiting..");
            try {
                Thread.sleep(100);
            } catch (final InterruptedException e) {
            }//from   ww w . j a v  a2 s.c  o  m
        }
        publishProgress(mAppContext.getResources().getString(R.string.please_stay_patient),
                mAppContext.getResources().getString(R.string.uploading_cells) + "(" + "Files" + ": "
                        + String.valueOf(cellFiles.size() - i) + ")",
                0);

        // enforce parallel execution on HONEYCOMB
        if (!mAnonymousUpload) {
            new AsyncUploader(this, mUser, mPassword, CELL_WEBSERVICE)
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, cellFiles.get(i));
            mActiveUploads += 1;
        } else if (mAnonymousUpload && (mToken != null)) {
            new AsyncUploader(this, mToken, CELL_ANONYMOUS_WEBSERVICE)
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, cellFiles.get(i));
            mActiveUploads += 1;
        } else {
            Log.e(TAG, "Neither user name nor token was available");
        }
    }
}

From source file:com.vadimfrolov.duorem.MainActivity.java

private void startTargetPolling() {
    Runnable pollTask = new Runnable() {
        @Override//from  ww w  .ja v  a2 s .  c  om
        public void run() {
            if (mIsConnected && mTarget != null) {
                RemoteCommand cmd = new RemoteCommand(mTarget, RemoteCommand.PING);
                (new RemoteAsyncTask(mDelegate)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, cmd);
            }
        }
    };
    if (mSch != null) {
        if (mPollFuture == null) {
            mPollFuture = mSch.scheduleWithFixedDelay(pollTask, 0, 5, TimeUnit.SECONDS);
        }

        // check if target is reachable right away. This is good for UI.
        boolean isAlive = true;
        try {
            Socket socket = new Socket(mTarget.ipAddress, Integer.parseInt(mTarget.sshPort));
        } catch (Exception e) {
            isAlive = false;
        }
        mTarget.isAlive = isAlive;
    }
}

From source file:com.cooperok.socialuser.vk.VkAccount.java

@Override
public void checkLikePage(String pageId, LikeCallback callback) {
    new LikeGroupCheckLoader(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageId);
}

From source file:com.cw.litenote.note.Note_adapter.java

private void showPictureView(int position, TouchImageView imageView, VideoView videoView,
        CustomWebView linkWebView, ProgressBar spinner) {
    String linkUri = db_page.getNoteLinkUri(position, true);
    String pictureUri = db_page.getNotePictureUri(position, true);
    String audioUri = db_page.getNoteAudioUri(position, true);
    String drawingUri = db_page.getNoteDrawingUri(position, true);

    // Check if Uri is for YouTube
    if (Util.isEmptyString(pictureUri) && Util.isYouTubeLink(linkUri)) {
        pictureUri = "http://img.youtube.com/vi/" + Util.getYoutubeId(linkUri) + "/0.jpg";//??? how to get this jpg for a playlist
        System.out.println("Note_adapter / _showPictureView / YouTube pictureUri = " + pictureUri);
    } else if (UtilImage.hasImageExtension(drawingUri, act))
        pictureUri = drawingUri;//w  w w  .  java2 s  .  co  m

    // show image view
    if (UtilImage.hasImageExtension(pictureUri, act)
            || (Util.isEmptyString(pictureUri) && Util.isEmptyString(audioUri) && Util.isEmptyString(linkUri))) // for wrong path icon
    {
        System.out.println("Note_adapter / _showPictureView / show image view");
        videoView.setVisibility(View.GONE);
        linkWebView.setVisibility(View.GONE);
        UtilVideo.mVideoView = null;
        imageView.setVisibility(View.VISIBLE);
        showImageByTouchImageView(spinner, imageView, pictureUri, position);
    }
    // show video view
    else if (UtilVideo.hasVideoExtension(pictureUri, act)) {
        System.out.println("Note_adapter / _showPictureView / show video view");
        linkWebView.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
        videoView.setVisibility(View.VISIBLE);
    }
    // show audio thumb nail view
    else if (Util.isEmptyString(pictureUri) && !Util.isEmptyString(audioUri)) {
        System.out.println("Note_adapter / _showPictureView / show audio thumb nail view");
        videoView.setVisibility(View.GONE);
        UtilVideo.mVideoView = null;
        linkWebView.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        try {
            AsyncTaskAudioBitmap audioAsyncTask;
            audioAsyncTask = new AsyncTaskAudioBitmap(act, audioUri, imageView, null, false);
            audioAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Searching media ...");
        } catch (Exception e) {
            System.out.println("Note_adapter / _AsyncTaskAudioBitmap / exception");
        }
    }
    // show link thumb view
    else if (Util.isEmptyString(pictureUri) && Util.isEmptyString(audioUri) && !Util.isEmptyString(linkUri)) {
        System.out.println("Note_adapter / _showPictureView / show link thumb view");
        videoView.setVisibility(View.GONE);
        UtilVideo.mVideoView = null;
        imageView.setVisibility(View.GONE);
        linkWebView.setVisibility(View.VISIBLE);
    } else
        System.out.println("Note_adapter / _showPictureView / show none");
}

From source file:com.appnexus.opensdkapp.MainActivity.java

synchronized public void readFromFile() {
    Clog.d(Constants.BASE_LOG_TAG, "Reading log file");

    ReadLogFileTask task = new ReadLogFileTask();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {//from   ww w.j  a v a  2s . c om
        task.execute();
    }

}

From source file:com.pcinpact.ListeArticlesActivity.java

@SuppressLint("NewApi")
private void telechargeListeArticles() {
    // Uniquement si on est pa&s dj en train de faire un refresh...
    if (DLinProgress == 0) {
        // Le retour en GUI
        nouveauChargementGUI();/*from  w  w w. ja v  a2s  . c o m*/

        // Ma tche de DL
        AsyncHTMLDownloader monAHD = new AsyncHTMLDownloader(getApplicationContext(), this,
                Constantes.HTML_LISTE_ARTICLES, Constantes.NEXT_INPACT_URL, 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();
        }
    }
}

From source file:ru.valle.safetrade.BuyActivity.java

private void loadState(final long id) {
    cancelAllTasks();/*from w w w  .  j a v a  2 s  .c  om*/
    loadStateTask = new AsyncTask<Void, Void, TradeRecord>() {
        @Override
        protected TradeRecord doInBackground(Void... params) {
            SQLiteDatabase db = DatabaseHelper.getInstance(BuyActivity.this).getReadableDatabase();
            Cursor cursor = db.query(DatabaseHelper.TABLE_HISTORY, null, BaseColumns._ID + "=?",
                    new String[] { String.valueOf(id) }, null, null, null);
            ArrayList<TradeRecord> tradeRecords = DatabaseHelper.readTradeRecords(cursor);
            return tradeRecords.isEmpty() ? null : tradeRecords.get(0);
        }

        @Override
        protected void onPostExecute(TradeRecord tradeRecord) {
            tradeInfo = tradeRecord;
            loadStateTask = null;
            rowId = tradeRecord.id;
            encryptedPrivateKeyView.setText(tradeRecord.encryptedPrivateKey);
            addressView.setText(tradeRecord.address);
            confirmationCodeView.setText(tradeRecord.confirmationCode);
            intermediateCodeView.setText(tradeRecord.intermediateCode);
            MainActivity.updateBalance(BuyActivity.this, id, tradeInfo.address, new Listener<AddressState>() {
                @Override
                public void onSuccess(AddressState result) {
                    if (result != null) {
                        balanceView.setText(BTCUtils.formatValue(result.getBalance()) + " BTC");
                    }
                }
            });
        }
    };
    if (Build.VERSION.SDK_INT >= 11) {
        loadStateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        loadStateTask.execute();
    }
}