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.android.launcher2.AsyncTaskCallback.java

/**
 * Creates and executes a new AsyncTask to load a page of widget previews.
 *//*from  w w w .  jav  a 2s .  c  om*/
private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, int cellWidth, int cellHeight,
        int cellCountX) {

    // Prune all tasks that are no longer needed
    Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
    while (iter.hasNext()) {
        AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
        int taskPage = task.page;
        if (taskPage < getAssociatedLowerPageBound(mCurrentPage)
                || taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
            task.cancel(false);
            iter.remove();
        } else {
            task.setThreadPriority(getThreadPriorityForPage(taskPage));
        }
    }

    // We introduce a slight delay to order the loading of side pages so that we don't thrash
    final int sleepMs = getSleepForPage(page);
    AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
            new AsyncTaskCallback() {
                @Override
                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
                    try {
                        try {
                            Thread.sleep(sleepMs);
                        } catch (Exception e) {
                        }
                        loadWidgetPreviewsInBackground(task, data);
                    } finally {
                        if (task.isCancelled()) {
                            data.cleanup(true);
                        }
                    }
                }
            }, new AsyncTaskCallback() {
                @Override
                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
                    mRunningTasks.remove(task);
                    if (task.isCancelled())
                        return;
                    // do cleanup inside onSyncWidgetPageItems
                    onSyncWidgetPageItems(data);
                }
            });

    // Ensure that the task is appropriately prioritized and runs in parallel
    AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadWidgetPreviewData);
    t.setThreadPriority(getThreadPriorityForPage(page));
    t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
    mRunningTasks.add(t);
}

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

private void handleImport(final Intent data) {
    new AsyncTask<Object, Object, Throwable>() {
        @Override//from w  w  w . ja va  2s  . co m
        protected Throwable doInBackground(Object... objects) {
            InputStream in = null;
            try {
                Log.i(TAG, "Reading URI=" + data.getData());
                ContentResolver resolver = getContentResolver();
                String[] streamTypes = resolver.getStreamTypes(data.getData(), "*/*");
                String streamType = (streamTypes == null || streamTypes.length == 0 ? "*/*" : streamTypes[0]);
                AssetFileDescriptor descriptor = resolver.openTypedAssetFileDescriptor(data.getData(),
                        streamType, null);
                in = descriptor.createInputStream();
                xmlImport(in);
                return null;
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                return ex;
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
            }
        }

        @Override
        protected void onPostExecute(Throwable ex) {
            if (running) {
                if (ex == null) {
                    Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG).show();
                    ServiceSinkhole.reloadStats("import", ActivitySettings.this);
                    // Update theme, request permissions
                    recreate();
                } else
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.phonemetra.turbo.launcher.AsyncTaskCallback.java

/**
 * Creates and executes a new AsyncTask to load a page of widget previews.
 */// w w w . ja v  a  2s . c o  m
private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, int cellWidth, int cellHeight,
        int cellCountX) {

    // Prune all tasks that are no longer needed
    Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
    while (iter.hasNext()) {
        AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
        int taskPage = task.page;
        if (taskPage < getAssociatedLowerPageBound(mCurrentPage)
                || taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
            task.cancel(false);
            iter.remove();
        } else {
            task.setThreadPriority(getThreadPriorityForPage(taskPage));
        }
    }

    // We introduce a slight delay to order the loading of side pages so that we don't thrash
    final int sleepMs = getSleepForPage(page);
    AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
            new AsyncTaskCallback() {
                @Override
                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
                    try {
                        try {
                            Thread.sleep(sleepMs);
                        } catch (Exception e) {
                        }
                        loadWidgetPreviewsInBackground(task, data);
                    } finally {
                        if (task.isCancelled()) {
                            data.cleanup(true);
                        }
                    }
                }
            }, new AsyncTaskCallback() {
                @Override
                public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
                    mRunningTasks.remove(task);
                    if (task.isCancelled())
                        return;
                    // do cleanup inside onSyncWidgetPageItems
                    onSyncWidgetPageItems(data, false);
                }
            }, getWidgetPreviewLoader());

    // Ensure that the task is appropriately prioritized and runs in parallel
    AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadWidgetPreviewData);
    t.setThreadPriority(getThreadPriorityForPage(page));
    t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
    mRunningTasks.add(t);
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle != null && mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }//from  ww  w.  j  a  va 2 s.  c  o  m
    // Handle action buttons
    MainFragment ma = null;
    try {
        TabFragment tabFragment = getFragment();
        if (tabFragment != null)
            ma = (MainFragment) tabFragment.getTab();
    } catch (Exception e) {
    }

    switch (item.getItemId()) {
    case R.id.home:
        if (ma != null)
            ma.home();
        break;
    case R.id.history:
        if (ma != null)
            GeneralDialogCreation.showHistoryDialog(dataUtils, utils, ma, getAppTheme());
        break;
    case R.id.sethome:
        if (ma == null)
            return super.onOptionsItemSelected(item);
        final MainFragment main = ma;
        if (main.openMode != OpenMode.FILE && main.openMode != OpenMode.ROOT) {
            Toast.makeText(mainActivity, R.string.not_allowed, Toast.LENGTH_SHORT).show();
            break;
        }
        final MaterialDialog dialog = GeneralDialogCreation.showBasicDialog(mainActivity,
                BaseActivity.accentSkin, getAppTheme(),
                new String[] { getResources().getString(R.string.questionset),
                        getResources().getString(R.string.setashome), getResources().getString(R.string.yes),
                        getResources().getString(R.string.no), null });
        dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                main.home = main.CURRENT_PATH;
                updatePaths(main.no);
                dialog.dismiss();
            }
        });
        dialog.show();
        break;
    case R.id.exit:
        finish();
        break;
    case R.id.sort:
        Fragment fragment = getDFragment();
        if (fragment.getClass().getName().contains("AppsList"))
            GeneralDialogCreation.showSortDialog((AppsList) fragment, getAppTheme());
        break;
    case R.id.sortby:
        if (ma != null)
            GeneralDialogCreation.showSortDialog(ma, getAppTheme());
        break;
    case R.id.dsort:
        if (ma == null)
            return super.onOptionsItemSelected(item);
        String[] sort = getResources().getStringArray(R.array.directorysortmode);
        MaterialDialog.Builder builder = new MaterialDialog.Builder(mainActivity);
        builder.theme(getAppTheme().getMaterialDialogTheme());
        builder.title(R.string.directorysort);
        int current = Integer.parseInt(sharedPref.getString("dirontop", "0"));

        final MainFragment mainFrag = ma;

        builder.items(sort).itemsCallbackSingleChoice(current, new MaterialDialog.ListCallbackSingleChoice() {
            @Override
            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                sharedPref.edit().putString("dirontop", "" + which).commit();
                mainFrag.getSortModes();
                mainFrag.updateList();
                dialog.dismiss();
                return true;
            }
        });
        builder.build().show();
        break;
    case R.id.hiddenitems:
        GeneralDialogCreation.showHiddenDialog(dataUtils, utils, ma, getAppTheme());
        break;
    case R.id.view:
        if (ma.IS_LIST) {
            if (dataUtils.getListfiles().contains(ma.CURRENT_PATH)) {
                dataUtils.getListfiles().remove(ma.CURRENT_PATH);
                grid.removePath(ma.CURRENT_PATH, DataUtils.LIST);
            }
            grid.addPath(null, ma.CURRENT_PATH, DataUtils.GRID, 0);
            dataUtils.getGridFiles().add(ma.CURRENT_PATH);
        } else {
            if (dataUtils.getGridFiles().contains(ma.CURRENT_PATH)) {
                dataUtils.getGridFiles().remove(ma.CURRENT_PATH);
                grid.removePath(ma.CURRENT_PATH, DataUtils.GRID);
            }
            grid.addPath(null, ma.CURRENT_PATH, DataUtils.LIST, 0);
            dataUtils.getListfiles().add(ma.CURRENT_PATH);
        }
        ma.switchView();
        break;
    case R.id.paste:
        String path = ma.CURRENT_PATH;
        ArrayList<BaseFile> arrayList = COPY_PATH != null ? COPY_PATH : MOVE_PATH;
        boolean move = MOVE_PATH != null;
        new CopyFileCheck(ma, path, move, mainActivity, BaseActivity.rootMode)
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, arrayList);
        COPY_PATH = null;
        MOVE_PATH = null;
        invalidatePasteButton(item);
        break;
    case R.id.extract:
        Fragment fragment1 = getSupportFragmentManager().findFragmentById(R.id.content_frame);
        if (fragment1.getClass().getName().contains("ZipViewer"))
            mainActivityHelper.extractFile(((ZipViewer) fragment1).f);
        break;
    case R.id.search:
        View searchItem = toolbar.findViewById(R.id.search);
        searchViewEditText.setText("");
        searchItem.getLocationOnScreen(searchCoords);
        revealSearchView();
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.auratech.launcher.Workspace.java

protected void setWallpaperDimension() {
    new AsyncTask<Void, Void, Void>() {
        public Void doInBackground(Void... args) {
            String spKey = WallpaperCropActivity.getSharedPreferencesKey();
            SharedPreferences sp = mLauncher.getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
            LauncherWallpaperPickerActivity.suggestWallpaperDimension(mLauncher.getResources(), sp,
                    mLauncher.getWindowManager(), mWallpaperManager);
            return null;
        }//from w w w.j  a  v a2s .  c o  m
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}

From source file:com.fairphone.fplauncher3.Workspace.java

protected void setWallpaperDimension() {
    new AsyncTask<Void, Void, Void>() {
        public Void doInBackground(Void... args) {
            String spKey = WallpaperCropActivity.getSharedPreferencesKey();
            SharedPreferences sp = mLauncher.getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
            LauncherWallpaperPickerActivity.suggestWallpaperDimension(mLauncher.getResources(), sp,
                    mLauncher.getWindowManager(), mWallpaperManager, Launcher.overrideWallpaperDimensions());
            return null;
        }// www.j av a 2 s  .  c  om

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            mLauncher.updateDarknessOverlay();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}

From source file:com.klinker.android.launcher.launcher3.Workspace.java

protected void setWallpaperDimension() {
    new AsyncTask<Void, Void, Void>() {
        public Void doInBackground(Void... args) {
            String spKey = LauncherFiles.WALLPAPER_CROP_PREFERENCES_KEY;
            SharedPreferences sp = mLauncher.getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
            WallpaperUtils.suggestWallpaperDimension(mLauncher.getResources(), sp, mLauncher.getWindowManager(),
                    mWallpaperManager, mLauncher.overrideWallpaperDimensions());
            return null;
        }/*from  ww  w  . j av  a 2  s . c  o m*/
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}

From source file:org.openhab.habdroid.ui.OpenHABMainActivity.java

private void gcmRegisterBackground() {
    Crittercism.setUsername(openHABUsername);
    OpenHABMainActivity.GCM_SENDER_ID = null;
    // if no notification settings can be constructed, no GCM registration can be made.
    if (getNotificationSettings() == null)
        return;/*w  w  w .j  a va 2  s. c om*/

    if (mGcm == null)
        mGcm = GoogleCloudMessaging.getInstance(getApplicationContext());

    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
            GoogleCloudMessageConnector connector = new GoogleCloudMessageConnector(getNotificationSettings(),
                    deviceId, mGcm);

            if (connector.register()) {
                OpenHABMainActivity.GCM_SENDER_ID = getNotificationSettings().getSenderId();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String regId) {
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
}

From source file:com.android.launcher3.Workspace.java

protected void setWallpaperDimension() {
    new AsyncTask<Void, Void, Void>() {
        public Void doInBackground(Void... args) {
            String spKey = WallpaperCropActivity.getSharedPreferencesKey();
            SharedPreferences sp = mLauncher.getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
            LauncherWallpaperPickerActivity.suggestWallpaperDimension(mLauncher.getResources(), sp,
                    mLauncher.getWindowManager(), mWallpaperManager, mLauncher.overrideWallpaperDimensions());
            return null;
        }//w w w. j av  a  2s.co  m
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}

From source file:com.example.camera2raw.Camera2RawFragment.java

/**
 * If the given request has been completed, remove it from the queue of active requests and
 * send an {@link ImageSaver} with the results from this request to a background thread to
 * save a file.//from w  w  w.j ava2s  . c o  m
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 *
 * @param requestId the ID of the {@link CaptureRequest} to handle.
 * @param builder   the {@link ImageSaverBuilder} for this request.
 * @param queue     the queue to remove this request from, if completed.
 */
private void handleCompletionLocked(int requestId, ImageSaverBuilder builder,
        TreeMap<Integer, ImageSaverBuilder> queue) {
    if (builder == null)
        return;
    ImageSaver saver = builder.buildIfComplete();
    if (saver != null) {
        queue.remove(requestId);
        AsyncTask.THREAD_POOL_EXECUTOR.execute(saver);
    }
}