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:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

/**
 * Merge the tabs of the other Chrome instance into this instance by reading its tab metadata
 * file and tab state files.//from w ww . j  a  va  2  s.  co  m
 *
 * This method should be called after a change in activity state indicates that a merge is
 * necessary. #loadState() will take care of merging states on application cold start if needed.
 *
 * If there is currently a merge or load in progress then this method will return early.
 */
public void mergeState() {
    if (mLoadInProgress || mPersistencePolicy.isMergeInProgress() || !mTabsToRestore.isEmpty()) {
        Log.e(TAG, "Tab load still in progress when merge was attempted.");
        return;
    }

    // Initialize variables.
    mCancelNormalTabLoads = false;
    mCancelIncognitoTabLoads = false;
    mNormalTabsRestored = new SparseIntArray();
    mIncognitoTabsRestored = new SparseIntArray();

    try {
        long time = SystemClock.uptimeMillis();
        // Read the tab state metadata file.
        DataInputStream stream = startFetchTabListTask(AsyncTask.SERIAL_EXECUTOR,
                mPersistencePolicy.getStateToBeMergedFileName()).get();

        // Return early if the stream is null, which indicates there isn't a second instance
        // to merge.
        if (stream == null)
            return;
        logExecutionTime("MergeStateInternalFetchTime", time);
        mPersistencePolicy.setMergeInProgress(true);
        readSavedStateFile(stream, createOnTabStateReadCallback(mTabModelSelector.isIncognitoSelected(), true),
                null, true);
        logExecutionTime("MergeStateInternalTime", time);
    } catch (Exception e) {
        // Catch generic exception to prevent a corrupted state from crashing app.
        Log.d(TAG, "meregeState exception: " + e.toString(), e);
    }

    // Restore the tabs from the second activity asynchronously.
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            mMergeTabCount = mTabsToRestore.size();
            mRestoreMergedTabsStartTime = SystemClock.uptimeMillis();
            restoreTabs(false);
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:org.telegram.messenger.support.JobIntentService.java

void ensureProcessorRunningLocked(boolean reportStarted) {
    if (mCurProcessor == null) {
        mCurProcessor = new CommandProcessor();
        if (mCompatWorkEnqueuer != null && reportStarted) {
            mCompatWorkEnqueuer.serviceProcessingStarted();
        }/*w  w  w.j  av  a 2  s. c  om*/
        if (DEBUG)
            Log.d(TAG, "Starting processor: " + mCurProcessor);
        mCurProcessor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}

From source file:com.SecUpwN.AIMSICD.activities.MapViewerOsmDroid.java

/**
 *  Description:    Loads Signal Strength Database details to plot on the map,
 *                  only entries which have a location (lon, lat) are used.
 *
 *
 *///  w  w w. j  av a2s .c  o m
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            final int SIGNAL_SIZE_RATIO = 15; // A scale factor to draw BTS Signal circles
            int signal;

            mCellTowerGridMarkerClusterer.getItems().clear();
            loadOpenCellIDMarkers();

            LinkedList<CellTowerMarker> items = new LinkedList<>();

            mDbHelper.open();
            Cursor c = null;
            try {
                // Grab cell data from CELL_TABLE (cellinfo) --> DBi_bts
                c = mDbHelper.getCellData();
            } catch (IllegalStateException ix) {
                Log.e(TAG, ix.getMessage(), ix);
            }
            if (c != null && c.moveToFirst()) {
                do {
                    // The indexing here is that of the Cursor and not the DB table itself
                    final int cellID = c.getInt(0); // CID
                    final int lac = c.getInt(1); // LAC
                    final int net = c.getInt(2); // RAT
                    final int mcc = c.getInt(6); // MCC
                    final int mnc = c.getInt(7); // MNC
                    final double dlat = Double.parseDouble(c.getString(3)); // Lat
                    final double dlng = Double.parseDouble(c.getString(4)); // Lon
                    if (dlat == 0.0 && dlng == 0.0) {
                        continue;
                    }
                    signal = c.getInt(5); // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    if (signal <= 0) {
                        signal = 20;
                    }

                    if ((dlat != 0.0) || (dlng != 0.0)) {
                        loc = new GeoPoint(dlat, dlng);

                        CellTowerMarker ovm = new CellTowerMarker(mContext, mMap, "Cell ID: " + cellID, "", loc,
                                new MarkerData("" + cellID, "" + loc.getLatitude(), "" + loc.getLongitude(),
                                        "" + lac, "" + mcc, "" + mnc, "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));
                        items.add(ovm);

                    }

                } while (c.moveToNext());
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(MapViewerOsmDroid.this, getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMCC();
                    double[] d = mDbHelper.getDefaultLocation(mcc);
                    ret = new GeoPoint(d[0], d[1]);
                } catch (Exception e) {
                    Log.e("map", "Error getting default location!", e);
                }
            }
            if (c != null && !c.isClosed()) {
                c.close();
            }
            mDbHelper.close();

            // plot neighbouring cells
            while (mAimsicdService == null)
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighbouringCells();
            for (Cell cell : nc) {
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(mContext, mMap,
                            getString(R.string.cell_id_label) + cell.getCID(), "", loc,
                            new MarkerData("" + cell.getCID(), "" + loc.getLatitude(), "" + loc.getLongitude(),
                                    "" + cell.getLAC(), "" + cell.getMCC(), "" + cell.getMNC(), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    Log.e("map", "Error plotting neighbouring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:dev.ukanth.ufirewall.MainActivity.java

/**
 * If the applications are cached, just show them, otherwise load and show
 *///from w  ww  . j a  va2  s.  c o m
private void showOrLoadApplications() {
    //nocache!!
    (new GetAppList()).setContext(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:eu.faircode.netguard.ActivityLog.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final File pcap_file = new File(getDir("data", MODE_PRIVATE), "netguard.pcap");

    switch (item.getItemId()) {
    case android.R.id.home:
        Log.i(TAG, "Up");
        NavUtils.navigateUpFromSameTask(this);
        return true;

    case R.id.menu_protocol_udp:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_udp", item.isChecked()).apply();
        updateAdapter();/*from   w w w.ja  v a 2 s  .co  m*/
        return true;

    case R.id.menu_protocol_tcp:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_tcp", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_protocol_other:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("proto_other", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_traffic_allowed:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("traffic_allowed", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_traffic_blocked:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("traffic_blocked", item.isChecked()).apply();
        updateAdapter();
        return true;

    case R.id.menu_log_live:
        item.setChecked(!item.isChecked());
        live = item.isChecked();
        if (live) {
            DatabaseHelper.getInstance(this).addLogChangedListener(listener);
            updateAdapter();
        } else
            DatabaseHelper.getInstance(this).removeLogChangedListener(listener);
        return true;

    case R.id.menu_refresh:
        updateAdapter();
        return true;

    case R.id.menu_log_resolve:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("resolve", item.isChecked()).apply();
        adapter.setResolve(item.isChecked());
        adapter.notifyDataSetChanged();
        return true;

    case R.id.menu_log_organization:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("organization", item.isChecked()).apply();
        adapter.setOrganization(item.isChecked());
        adapter.notifyDataSetChanged();
        return true;

    case R.id.menu_pcap_enabled:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("pcap", item.isChecked()).apply();
        ServiceSinkhole.setPcap(item.isChecked(), ActivityLog.this);
        return true;

    case R.id.menu_pcap_export:
        startActivityForResult(getIntentPCAPDocument(), REQUEST_PCAP);
        return true;

    case R.id.menu_log_clear:
        new AsyncTask<Object, Object, Object>() {
            @Override
            protected Object doInBackground(Object... objects) {
                DatabaseHelper.getInstance(ActivityLog.this).clearLog(-1);
                if (prefs.getBoolean("pcap", false)) {
                    ServiceSinkhole.setPcap(false, ActivityLog.this);
                    if (pcap_file.exists() && !pcap_file.delete())
                        Log.w(TAG, "Delete PCAP failed");
                    ServiceSinkhole.setPcap(true, ActivityLog.this);
                } else {
                    if (pcap_file.exists() && !pcap_file.delete())
                        Log.w(TAG, "Delete PCAP failed");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object result) {
                if (running)
                    updateAdapter();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return true;

    case R.id.menu_log_support:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("https://github.com/M66B/NetGuard/blob/master/FAQ.md#FAQ27"));
        if (getPackageManager().resolveActivity(intent, 0) != null)
            startActivity(intent);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.appolis.receiving.AcReceiveOptionMove.java

/**
 * commit item details/*from  ww  w .  j av a2 s .co  m*/
 * @param locationTo location to move
 */
private void commitData(String locationTo) {
    OptionMoveAsyn mLoadDataTask = new OptionMoveAsyn(this, locationTo);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mLoadDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        mLoadDataTask.execute();
    }
}

From source file:joshuatee.wx.StormReportsActivity.java

public void RadarProdShow(int id, String prod, Boolean show_dot) {

    String x = x_arr[id];/* ww w . j ava 2  s  . c  om*/
    String y = y_arr[id];
    String time = time_arr[id];

    String rid1 = UtilityLocation.GetNearestRid(getBaseContext(), x, y);
    time = UtilityStringExternal.truncate(time, 3);

    if (prod.equals("TR0") || prod.equals("TV0")) {
        rid1 = UtilityNexrad.GetTDWRFromRID(rid1);
    }

    // FIXME 6am-6am CST so need to account for DST starting in Nov from 4 to 5 hrs
    if (Integer.parseInt(time_arr[id]) < 1000) {
        month_str = String.format(Locale.US, "%02d", pMonth + 1);
        day_str = String.format(Locale.US, "%02d", pDay + 1);
        year_str = Integer.toString(pYear);
        year_str = year_str.substring(2, 4);
        date = year_str + month_str + day_str;
        iowa_meso_url = "http://mesonet.agron.iastate.edu/archive/data/20" + year_str + "/" + month_str + "/"
                + day_str + "/GIS/ridge/";
        iowa_meso_str = "20" + year_str + month_str + day_str;
    }

    String full_url = iowa_meso_url + rid1 + "/" + prod + "/";
    String pattern = rid1 + "_" + prod + "_" + iowa_meso_str + time;

    // FIXME
    // implement method to find closest rid like AU

    if (!show_dot) {
        x = "0.0";
        y = "0.0";
    }

    //Log.i("wx",full_url);

    new GetImage().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, full_url, pattern, rid1, x, y);

}

From source file:com.orbar.pxdemo.ImageView.FivePXImageFragment.java

private void submitComment() {
    // TODO Auto-generated method stub

    submitCommentBody = (EditText) rootView.findViewById(R.id.submit_comment_body);

    String commentBody = submitCommentBody.getText().toString();

    if (mLoginManager.isLoggedIn()) {

        mPostCommentImage = new PostCommentImage(getActivity(), mFiveZeroZeroImageAPIBuilder, mLoginManager,
                mFiveZeroZeroImageBean, mCommentsAdapter, commentBody, submitCommentBody);
        mPostCommentImage.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } else {/*from ww w . j a  v a 2s. c o  m*/
        reason = LOGGING_REASON.COMMENT;
        login();
    }

}

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

private void checkForLocaleChange() {
    if (sLocaleConfiguration == null) {
        new AsyncTask<Void, Void, LocaleConfiguration>() {
            @Override/* ww  w  .  ja v  a  2s. co  m*/
            protected LocaleConfiguration doInBackground(Void... unused) {
                LocaleConfiguration localeConfiguration = new LocaleConfiguration();
                readConfiguration(Launcher.this, localeConfiguration);
                return localeConfiguration;
            }

            @Override
            protected void onPostExecute(LocaleConfiguration result) {
                sLocaleConfiguration = result;
                checkForLocaleChange(); // recursive, but now with a locale configuration
            }
        }.execute();
        return;
    }

    final Configuration configuration = getResources().getConfiguration();

    final String previousLocale = sLocaleConfiguration.locale;
    final String locale = configuration.locale.toString();

    final int previousMcc = sLocaleConfiguration.mcc;
    final int mcc = configuration.mcc;

    final int previousMnc = sLocaleConfiguration.mnc;
    final int mnc = configuration.mnc;

    boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;

    if (localeChanged) {
        sLocaleConfiguration.locale = locale;
        sLocaleConfiguration.mcc = mcc;
        sLocaleConfiguration.mnc = mnc;

        mIconCache.flush();

        final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
        new AsyncTask<Void, Void, Void>() {
            public Void doInBackground(Void... args) {
                writeConfiguration(Launcher.this, localeConfiguration);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
    }
}

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

/**
 * Start new audio/*www  . ja va 2 s  .  c om*/
 */
private void startNewAudio() {
    System.out.println(
            "AudioPlayer_page / _startNewAudio / Audio_manager.mAudioPos = " + Audio_manager.mAudioPos);

    // remove call backs to make sure next toast will appear soon
    if (mAudioHandler != null)
        mAudioHandler.removeCallbacks(page_runnable);
    mAudioHandler = null;
    mAudioHandler = new Handler();

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

    // verify audio URL
    Async_audioUrlVerify.mIsOkUrl = false;

    if ((Audio_manager.getAudioPlayMode() == Audio_manager.PAGE_PLAY_MODE)
            && (Audio_manager.getCheckedAudio(Audio_manager.mAudioPos) == 0)) {
        mAudioHandler.postDelayed(page_runnable, Util.oneSecond / 4);
    } else {
        mAudioUrlVerifyTask = new Async_audioUrlVerify(act,
                mAudioManager.getAudioStringAt(Audio_manager.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) {
            showAudioPanel(act, true);

            // launch handler
            if ((Audio_manager.getPlayerState() != Audio_manager.PLAYER_AT_STOP)
                    && (Audio_manager.getAudioPlayMode() == Audio_manager.PAGE_PLAY_MODE)) {
                mAudioHandler.postDelayed(page_runnable, Util.oneSecond / 4);
            }

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

            if (Build.VERSION.SDK_INT >= 21) {
                MediaControllerCompat.getMediaController(MainAct.mAct).getTransportControls()
                        .playFromUri(Uri.parse(audioUrl_page), null);

                MediaControllerCompat.getMediaController(MainAct.mAct).getTransportControls().play();
            } else {
                BackgroundAudioService.mMediaPlayer = new MediaPlayer();
                BackgroundAudioService.mMediaPlayer.reset();
                try {
                    BackgroundAudioService.mMediaPlayer.setDataSource(act, Uri.parse(audioUrl_page));

                    // prepare the MediaPlayer to play, this will delay system response
                    BackgroundAudioService.mMediaPlayer.prepare();
                    setAudioListeners();
                } catch (Exception e) {
                    Toast.makeText(act, R.string.audio_message_could_not_open_file, Toast.LENGTH_SHORT).show();
                    Audio_manager.stopAudioPlayer();
                }
            }
        }
    }

}