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.guardtrax.ui.screens.SplashScreen.java

private void syncDB() {
    //only sync registered devices, not those with dummy license
    if (!Utility.deviceRegistered()) {
        Toast.makeText(SplashScreen.this, "Device not registered!", Toast.LENGTH_LONG).show();
        syncComplete = true;/*from  w w  w . j a v a  2 s. co m*/
    } else {
        syncdb = new SyncDB();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            syncdb.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            syncdb.execute();
    }
}

From source file:com.netdoers.utils.ApplicationLoader.java

private void registerInBackground() {
    AsyncTask<String, String, Boolean> task = new AsyncTask<String, String, Boolean>() {
        @Override//w w  w  . j a  v a  2  s  .  c  o m
        protected Boolean doInBackground(String... objects) {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(applicationContext);
            }
            int count = 0;
            while (count < 100) {
                try {
                    count++;
                    regid = gcm.register(BuildVars.GCM_SENDER_ID);
                    storeRegistrationId(applicationContext, regid);
                    if (!ApplicationLoader.getSharedPreferences().getBoolean("isRegisteredToServer", false)) {
                        sendRegistrationIdToBackend();
                    } else {
                        Log.i("AndroidToServer", "Already registered to server");
                    }
                    return true;
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                try {
                    if (count % 20 == 0) {
                        Thread.sleep(60000 * 30);
                    } else {
                        Thread.sleep(5000);
                    }
                } catch (InterruptedException e) {
                    FileLog.e("tmessages", e);
                }
            }
            return false;
        }
    };

    if (android.os.Build.VERSION.SDK_INT >= 11) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
    } else {
        task.execute(null, null, null);
    }
}

From source file:eu.power_switch.gui.adapter.RoomRecyclerViewAdapter.java

private void updateReceiverViews(final RoomRecyclerViewAdapter.ViewHolder holder, final Room room) {
    String inflaterString = Context.LAYOUT_INFLATER_SERVICE;
    LayoutInflater inflater = (LayoutInflater) fragmentActivity.getSystemService(inflaterString);

    // clear previous items
    holder.linearLayoutOfReceivers.removeAllViews();
    // add items/*from  w w  w .j  a  v  a  2 s .c  o  m*/
    for (final Receiver receiver : room.getReceivers()) {
        // create a new receiverRow for our current receiver and add it to
        // our table of all devices of our current room
        // the row will contain the device name and all buttons

        LinearLayout receiverLayout = (LinearLayout) inflater.inflate(R.layout.list_item_receiver,
                holder.linearLayoutOfReceivers, false);
        receiverLayout.setOrientation(LinearLayout.HORIZONTAL);
        holder.linearLayoutOfReceivers.addView(receiverLayout);

        // setup TextView to display device name
        TextView receiverName = (TextView) receiverLayout.findViewById(R.id.txt_name);
        receiverName.setText(receiver.getName());
        receiverName.setTextSize(18);

        TableLayout buttonLayout = (TableLayout) receiverLayout.findViewById(R.id.buttonLayout);
        int buttonsPerRow;
        if (receiver.getButtons().size() % 3 == 0) {
            buttonsPerRow = 3;
        } else {
            buttonsPerRow = 2;
        }

        int i = 0;
        final ArrayList<android.widget.Button> buttonViews = new ArrayList<>();
        long lastActivatedButtonId = receiver.getLastActivatedButtonId();
        TableRow buttonRow = null;
        for (final Button button : receiver.getButtons()) {
            final android.widget.Button buttonView = (android.widget.Button) inflater
                    .inflate(R.layout.simple_button, buttonRow, false);
            final ColorStateList defaultTextColor = buttonView.getTextColors(); //save original colors
            buttonViews.add(buttonView);
            buttonView.setText(button.getName());
            final int accentColor = ThemeHelper.getThemeAttrColor(fragmentActivity, R.attr.colorAccent);
            if (SmartphonePreferencesHandler.getHighlightLastActivatedButton() && lastActivatedButtonId != -1
                    && button.getId() == lastActivatedButtonId) {
                buttonView.setTextColor(accentColor);
            }
            buttonView.setOnClickListener(new android.widget.Button.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    if (SmartphonePreferencesHandler.getVibrateOnButtonPress()) {
                        VibrationHandler.vibrate(fragmentActivity,
                                SmartphonePreferencesHandler.getVibrationDuration());
                    }

                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            // send signal
                            ActionHandler.execute(fragmentActivity, receiver, button);
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            if (SmartphonePreferencesHandler.getHighlightLastActivatedButton()) {
                                for (android.widget.Button button : buttonViews) {
                                    if (button != v) {
                                        button.setTextColor(defaultTextColor);
                                    } else {
                                        button.setTextColor(accentColor);
                                    }
                                }
                            }
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });

            if (i == 0 || i % buttonsPerRow == 0) {
                buttonRow = new TableRow(fragmentActivity);
                buttonRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT));
                buttonRow.addView(buttonView);
                buttonLayout.addView(buttonRow);
            } else {
                buttonRow.addView(buttonView);
            }

            i++;
        }

        receiverLayout.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                ConfigureReceiverDialog configureReceiverDialog = ConfigureReceiverDialog
                        .newInstance(receiver.getId());
                configureReceiverDialog.setTargetFragment(recyclerViewFragment, 0);
                configureReceiverDialog.show(fragmentActivity.getSupportFragmentManager(), null);
                return true;
            }
        });
    }
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

public Bitmap getPreview(final Object o) {
    final String name = getObjectName(o);
    final String packageName = getObjectPackage(o);
    // check if the package is valid
    synchronized (sInvalidPackages) {
        boolean packageValid = !sInvalidPackages.contains(packageName);
        if (!packageValid) {
            return null;
        }/*from  w  ww . j  a v a2 s  .  c  o  m*/
    }
    synchronized (mLoadedPreviews) {
        // check if it exists in our existing cache
        if (mLoadedPreviews.containsKey(name)) {
            WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
            Bitmap bitmap = bitmapReference.get();
            if (bitmap != null) {
                return bitmap;
            }
        }
    }

    Bitmap unusedBitmap = null;
    synchronized (mUnusedBitmaps) {
        // not in cache; we need to load it from the db
        while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
            Bitmap candidate = mUnusedBitmaps.remove(0).get();
            if (candidate != null && candidate.isMutable() && candidate.getWidth() == mPreviewBitmapWidth
                    && candidate.getHeight() == mPreviewBitmapHeight) {
                unusedBitmap = candidate;
            }
        }
        if (unusedBitmap != null) {
            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
            c.setBitmap(unusedBitmap);
            c.drawColor(0, PorterDuff.Mode.CLEAR);
            c.setBitmap(null);
        }
    }

    if (unusedBitmap == null) {
        unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight, Bitmap.Config.ARGB_8888);
    }
    Bitmap preview = readFromDb(name, unusedBitmap);

    if (preview != null) {
        synchronized (mLoadedPreviews) {
            mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
        }
        return preview;
    } else {
        // it's not in the db... we need to generate it
        final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
        preview = generatedPreview;
        if (preview != unusedBitmap) {
            throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
        }

        synchronized (mLoadedPreviews) {
            mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
        }

        // write to db on a thread pool... this can be done lazily and improves the performance
        // of the first time widget previews are loaded
        new AsyncTask<Void, Void, Void>() {
            public Void doInBackground(Void... args) {
                writeToDb(o, generatedPreview);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);

        return preview;
    }
}

From source file:com.cw.litenote.operation.audio.AudioPlayer_note.java

/**
 * Start new audio//from   w ww. j a  va  2s.  co m
 */
private void startNewAudio() {
    // remove call backs to make sure next toast will appear soon
    if (mAudioHandler != null)
        mAudioHandler.removeCallbacks(mRunOneTimeMode);
    mAudioHandler = null;
    mAudioHandler = new Handler();

    Audio_manager.isRunnableOn_page = false;
    Audio_manager.isRunnableOn_note = true;
    BackgroundAudioService.mMediaPlayer = null;

    // verify audio
    Async_audioUrlVerify.mIsOkUrl = false;

    mAudioUrlVerifyTask = new Async_audioUrlVerify(act, mAudioManager.getAudioStringAt(mAudioPos));
    mAudioUrlVerifyTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Searching media ...");

    while (!Async_audioUrlVerify.mIsOkUrl) {
        //wait for Url verification
        try {
            Thread.sleep(Util.oneSecond / 20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // prepare audio
    if (Async_audioUrlVerify.mIsOkUrl) {
        // launch handler
        if (Audio_manager.getPlayerState() != Audio_manager.PLAYER_AT_STOP) {
            if (Audio_manager.getAudioPlayMode() == Audio_manager.NOTE_PLAY_MODE) {
                mAudioHandler.postDelayed(mRunOneTimeMode, Util.oneSecond / 4);
            }
        }

        // during audio Preparing
        Async_audioPrepare mAsyncTaskAudioPrepare = new Async_audioPrepare(act);
        mAsyncTaskAudioPrepare.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Preparing to play ...");
    }

}

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

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {
        // Read weather condition ID from cursor

        iconView.setImageResource(R.drawable.ic_drawer);

        // Read date from cursor
        //long dateInMillis = cursor.getLong(ForecastFragment.COL_WEATHER_DATE);
        // Find TextView and set formatted date on it
        final String movieName = data.getString(ImdbFragment.COL_TMDBID);
        nameView.setText(movieName);/*from   w w w. j  a  va 2 s  .co m*/

        // Read weather forecast from cursor
        final String description = data.getString(ImdbFragment.COL_IMDBRATING);
        // Find TextView and set weather forecast on it
        descriptionView.setText(description);

        // Read user preference for metric or imperial temperature units
        // boolean isMetric = Utility.isMetric(context);

        // Read high temperature from cursor
        //double high = cursor.getDouble(ForecastFragment.COL_WEATHER_MAX_TEMP);
        final String reldate = data.getString(ImdbFragment.COL_IMDBID);
        relDateView.setText(reldate);

        // Read low temperature from cursor
        // double low = cursor.getDouble(ForecastFragment.COL_WEATHER_MIN_TEMP);
        String movieid = data.getString(ImdbFragment.COL_TEMP);
        movieIdView.setText(movieid);

        imdbimage.setImageResource(R.drawable.ic_drawer);

        imdbimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FetchRandomOmdb movieTask = new FetchRandomOmdb(getActivity());
                //  movieTask.execute(movieid);
                String[] params = { reldate, movieName };
                movieTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

                imdbrating.setText(description);
                imdbrating.setVisibility(View.VISIBLE);

            }
        });

        // We still need this for the share intent
        mForecast = String.format("%s - %s - %s", movieName, description, reldate);

        // If onCreateOptionsMenu has already happened, we need to update the share intent now.
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(createShareForecastIntent());
        }
    }
}

From source file:com.aegiswallet.actions.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    application = (PayBitsApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    smsTxnsPrefs = application.getSharedPreferences(getString(R.string.sms_transaction_filename),
            Context.MODE_PRIVATE);
    //smsTxnsPrefs.edit().clear().commit();
    wallet = application.getWallet();//  w  w w . j  ava 2  s.c om
    application.initializeShamirSecretSharing(context);

    checkIfAppInitiated();

    setContentView(R.layout.activity_main);
    getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getActionBar().setCustomView(R.layout.aegis_actionbar);

    openDrawerButton = (ImageButton) findViewById(R.id.action_bar_icon);
    openDrawerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mDrawerLayout != null) {
                if (mDrawerLayout.isDrawerOpen(Gravity.LEFT))
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                else
                    mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        }
    });

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    blockchainStatus = (TextView) findViewById(R.id.blockchain_status);
    blockchainStatus.setTypeface(BasicUtils.getCustomTypeFace(getBaseContext()));

    setupBlockchainBroadcastReceiver(blockchainStatus);

    GetCurrencyInfoTask currencyInfoTask = new GetCurrencyInfoTask(getApplicationContext());
    currencyInfoTask.execute();
    //currencyInfoTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);

    watchedBalanceLinearLayout = (LinearLayout) findViewById(R.id.watched_balance_view);

    walletBalanceView = (TextView) findViewById(R.id.wallet_balance);
    walletBalanceView.setTypeface(BasicUtils.getCustomTypeFace(getBaseContext()));

    if (!prefs.contains(Constants.CURRENCY_PREF_KEY)) {
        prefs.edit().putString(Constants.CURRENCY_PREF_KEY, "USD").commit();
    }

    walletWatchAddressBalanceView = (TextView) findViewById(R.id.watch_only_balance);

    updateMainViews();
    determineSelectedAddress();
    application.startBlockchainService(false);
    handleButtons();

    recentTransactions = (ArrayList<Transaction>) wallet.getRecentTransactions(50, true);
    transactionListAdapter = new TransactionListAdapter(this, R.layout.transaction_detail_row,
            recentTransactions, wallet);

    transactionListView = (ListView) findViewById(R.id.transaction_list);
    if (recentTransactions == null || recentTransactions.size() == 0)
        transactionListView.setEmptyView(findViewById(R.id.transaction_empty_view_main));

    transactionListView.setAdapter(transactionListAdapter);

    handlePendingTransactions();

    initiateHandlers(walletBalanceView);
    application.addWalletListener(balanceHandler);

    checkWalletEncryptionStatus();
    this.registerReceiver(receiver, new IntentFilter(PeerBlockchainService.ACTION_BLOCKCHAIN_STATE));

    doDrawerSetup();

    String message = getIntent().getStringExtra("message");
    if (message != null) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        getIntent().removeExtra("message");
    }

    nfcEnabled = prefs.contains(Constants.SHAMIR_ENCRYPTED_KEY) ? false : true;
    checkBackupDone();
    doBackupReminder();

    isServiceBound = this.bindService(new Intent(this, PeerBlockchainService.class),
            blockchainServiceConnection, Context.BIND_AUTO_CREATE);

    HandleSMSResponsesTask handleSMSResponsesTask = new HandleSMSResponsesTask(this);
    //handleSMSResponsesTask.execute();
    handleSMSResponsesTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);

    sendMessagesToWear();

}

From source file:com.example.amit.tellymoviebuzzz.ImdbFragment.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");

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

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

public void removeFromFavorites() {
    new AsyncTask<Void, Void, Void>() {

        @Override//from w w  w  .  j a  v  a  2 s.  c  o  m
        protected Void doInBackground(Void... params) {
            if (isFavorite()) {
                getContext().getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI,
                        MovieContract.MovieEntry.COLUMN_MOVIE_ID + " = " + mMovie.getId(), null);

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            updateFavoriteButtons();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.bukanir.android.activities.MoviesListActivity.java

private void handleSearchIntent(Intent intent) {
    Log.d(TAG, "handleSearchIntent");
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (Utils.isNetworkAvailable(this)) {
            Log.d(TAG, "networkAvailable");
            moviesTask = new MoviesTask();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                moviesTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, query, null);
            } else {
                moviesTask.execute(query, null);
            }/*from w  ww  . j  av  a 2  s  . c  o  m*/
        } else {
            Toast.makeText(this, getString(R.string.network_not_available), Toast.LENGTH_LONG).show();
        }
    }
}