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.ape.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   www .  ja  v a  2  s  .c  om
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 *
 * @param requestId the ID of the {@link CaptureRequest} to handle.
 * @param builder   the {@link ImageSaver.ImageSaverBuilder} for this request.
 * @param queue     the queue to remove this request from, if completed.
 */
private void handleCompletionLocked(int requestId, ImageSaver.ImageSaverBuilder builder,
        TreeMap<Integer, ImageSaver.ImageSaverBuilder> queue) {
    if (builder == null)
        return;
    ImageSaver saver = builder.buildIfComplete();
    if (saver != null) {
        queue.remove(requestId);
        AsyncTask.THREAD_POOL_EXECUTOR.execute(saver);
    }
}

From source file:com.igniva.filemanager.activities.MainActivity.java

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (requestCode == RC_SIGN_IN && !mGoogleApiKey && mGoogleApiClient != null) {
        new Thread(new Runnable() {
            @Override//w  w  w.  j a v a  2s . com
            public void run() {
                mIntentInProgress = false;
                mGoogleApiKey = true;
                // !mGoogleApiClient.isConnecting
                if (mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                } else
                    mGoogleApiClient.disconnect();

            }
        }).run();
    } else if (requestCode == image_selector_request_code) {
        if (Sp != null && intent != null && intent.getData() != null) {
            if (Build.VERSION.SDK_INT >= 19)
                getContentResolver().takePersistableUriPermission(intent.getData(),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Sp.edit().putString("drawer_header_path", intent.getData().toString()).commit();
            setDrawerHeaderBackground();
        }
    } else if (requestCode == 3) {
        String p = Sp.getString("URI", null);

        Uri oldUri = p != null ? Uri.parse(p) : null;
        Uri treeUri = null;
        if (responseCode == Activity.RESULT_OK) {
            // Get Uri from Storage Access Framework.
            treeUri = intent.getData();
            // Persist URI - this is required for verification of writability.
            if (treeUri != null)
                Sp.edit().putString("URI", treeUri.toString()).commit();
        }
        // If not confirmed SAF, or if still not writable, then revert settings.
        if (responseCode != Activity.RESULT_OK) {
            /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false,
                currentFolder);||!FileUtil.isWritableNormalOrSaf(currentFolder)
            */
            if (treeUri != null)
                Sp.edit().putString("URI", oldUri.toString()).commit();
            return;
        }

        // After confirmation, update stored value of folder.
        // Persist access permissions.
        final int takeFlags = intent.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
        switch (operation) {
        case DataUtils.DELETE://deletion
            new DeleteTask(null, mainActivity).execute((oparrayList));
            break;
        case DataUtils.COPY://copying
            Intent intent1 = new Intent(con, CopyService.class);
            intent1.putExtra("FILE_PATHS", (oparrayList));
            intent1.putExtra("COPY_DIRECTORY", oppathe);
            startService(intent1);
            break;
        case DataUtils.MOVE://moving
            new MoveFiles((oparrayList), ((Main) getFragment().getTab()),
                    ((Main) getFragment().getTab()).getActivity(), 0)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, path);
            break;
        case DataUtils.NEW_FOLDER://mkdir
            Main ma1 = ((Main) getFragment().getTab());
            mainActivityHelper.mkDir(RootHelper.generateBaseFile(new File(oppathe), true), ma1);
            break;
        case DataUtils.RENAME:
            mainActivityHelper.rename(HFile.LOCAL_MODE, (oppathe), (oppathe1), mainActivity,
                    BaseActivity.rootMode);
            Main ma2 = ((Main) getFragment().getTab());
            ma2.updateList();
            break;
        case DataUtils.NEW_FILE:
            Main ma3 = ((Main) getFragment().getTab());
            mainActivityHelper.mkFile(new HFile(HFile.LOCAL_MODE, oppathe), ma3);

            break;
        case DataUtils.EXTRACT:
            mainActivityHelper.extractFile(new File(oppathe));
            break;
        case DataUtils.COMPRESS:
            mainActivityHelper.compressFiles(new File(oppathe), oparrayList);
        }
        operation = -1;
    }
}

From source file:com.amaze.carbonfilemanager.fragments.MainFragment.java

public void onSearchCompleted(final String query) {
    if (!results) {
        // no results were found
        getLayoutElements().clear();//from w  w w  .j ava 2s. com
    }
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Collections.sort(getLayoutElements(), new FileListSorter(dsort, sortby, asc));
            return null;
        }

        @Override
        public void onPostExecute(Void c) {
            createViews(getLayoutElements(), true, (CURRENT_PATH), openMode, true, !IS_LIST);
            pathname.setText(MAIN_ACTIVITY.getString(R.string.empty));
            mFullPath.setText(MAIN_ACTIVITY.getString(R.string.searchresults) + " " + query);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:g7.bluesky.launcher3.Launcher.java

/**
 * Add a widget to the workspace./*from  ww  w . j av  a2s  .c o m*/
 *
 * @param appWidgetId The app widget id
 * @param cellInfo The position on screen where to create the widget.
 */
private void completeAddAppWidget(final int appWidgetId, long container, long screenId,
        AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
    if (appWidgetInfo == null) {
        appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
    }

    // Calculate the grid spans needed to fit this widget
    CellLayout layout = getCellLayout(container, screenId);

    int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
    int[] spanXY = getSpanForWidget(this, appWidgetInfo);

    // Try finding open space on Launcher screen
    // We have saved the position to which the widget was dragged-- this really only matters
    // if we are placing widgets on a "spring-loaded" screen
    int[] cellXY = mTmpAddItemCellCoordinates;
    int[] touchXY = mPendingAddInfo.dropPos;
    int[] finalSpan = new int[2];
    boolean foundCellSpan = false;
    if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
        cellXY[0] = mPendingAddInfo.cellX;
        cellXY[1] = mPendingAddInfo.cellY;
        spanXY[0] = mPendingAddInfo.spanX;
        spanXY[1] = mPendingAddInfo.spanY;
        foundCellSpan = true;
    } else if (touchXY != null) {
        // when dragging and dropping, just find the closest free spot
        int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1],
                spanXY[0], spanXY[1], cellXY, finalSpan);
        spanXY[0] = finalSpan[0];
        spanXY[1] = finalSpan[1];
        foundCellSpan = (result != null);
    } else {
        foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
    }

    if (!foundCellSpan) {
        if (appWidgetId != -1) {
            // Deleting an app widget ID is a void call but writes to disk before returning
            // to the caller...
            new AsyncTask<Void, Void, Void>() {
                public Void doInBackground(Void... args) {
                    mAppWidgetHost.deleteAppWidgetId(appWidgetId);
                    return null;
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
        }
        showOutOfSpaceMessage(isHotseatLayout(layout));
        return;
    }

    // Build Launcher-specific widget info and save to database
    LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider);
    launcherInfo.spanX = spanXY[0];
    launcherInfo.spanY = spanXY[1];
    launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
    launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
    launcherInfo.user = mAppWidgetManager.getUser(appWidgetInfo);

    LauncherModel.addItemToDatabase(this, launcherInfo, container, screenId, cellXY[0], cellXY[1], false);

    if (!mRestoring) {
        if (hostView == null) {
            // Perform actual inflation because we're live
            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
        } else {
            // The AppWidgetHostView has already been inflated and instantiated
            launcherInfo.hostView = hostView;
        }

        launcherInfo.hostView.setTag(launcherInfo);
        launcherInfo.hostView.setVisibility(View.VISIBLE);
        launcherInfo.notifyWidgetSizeChanged(this);

        mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, cellXY[0], cellXY[1],
                launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());

        addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
    }
    resetAddInfo();
}

From source file:me.ccrama.redditslide.Views.SubsamplingScaleImageView.java

private void execute(AsyncTask<Void, Void, ?> asyncTask) {
    if (parallelLoadingEnabled && VERSION.SDK_INT >= 11) {
        try {/*w  ww .  ja  v a2s .c  o m*/
            Field executorField = AsyncTask.class.getField("THREAD_POOL_EXECUTOR");
            Executor executor = (Executor) executorField.get(null);
            Method executeMethod = AsyncTask.class.getMethod("executeOnExecutor",
                    new Class[] { Executor.class, Object[].class });
            executeMethod.invoke(asyncTask, executor, null);
            return;
        } catch (Exception e) {
            Log.i(TAG,
                    "Failed to execute AsyncTask on thread pool executor, falling back to single threaded executor",
                    e);
        }
    }
    try {
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } catch (RejectedExecutionException e) {
        //todo catch gracefully
    }
}

From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java

protected ListenableFuture<Long> saveDraft() {
    final SettableFuture<Long> future = new SettableFuture<>();

    if (this.recipient == null) {
        future.set(threadId);/*  ww w.  ja v  a 2s. c o m*/
        return future;
    }

    final Drafts drafts = getDraftsForCurrentState();
    final long thisThreadId = this.threadId;
    final int thisDistributionType = this.distributionType;

    new AsyncTask<Long, Void, Long>() {
        @Override
        protected Long doInBackground(Long... params) {
            ThreadDatabase threadDatabase = DatabaseFactory.getThreadDatabase(ConversationActivity.this);
            DraftDatabase draftDatabase = DatabaseFactory.getDraftDatabase(ConversationActivity.this);
            long threadId = params[0];

            if (drafts.size() > 0) {
                if (threadId == -1)
                    threadId = threadDatabase.getThreadIdFor(getRecipient(), thisDistributionType);

                draftDatabase.insertDrafts(threadId, drafts);
                threadDatabase.updateSnippet(threadId, drafts.getSnippet(ConversationActivity.this),
                        drafts.getUriSnippet(), System.currentTimeMillis(), Types.BASE_DRAFT_TYPE, true);
            } else if (threadId > 0) {
                threadDatabase.update(threadId, false);
            }

            return threadId;
        }

        @Override
        protected void onPostExecute(Long result) {
            future.set(result);
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, thisThreadId);

    return future;
}

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

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (requestCode == RC_SIGN_IN && !mGoogleApiKey && mGoogleApiClient != null) {
        new Thread(new Runnable() {
            @Override// www  .  j  av  a 2  s  .  c o  m
            public void run() {
                mIntentInProgress = false;
                mGoogleApiKey = true;
                // !mGoogleApiClient.isConnecting
                if (mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                } else
                    mGoogleApiClient.disconnect();

            }
        }).run();
    } else if (requestCode == image_selector_request_code) {
        if (sharedPref != null && intent != null && intent.getData() != null) {
            if (SDK_INT >= 19)
                getContentResolver().takePersistableUriPermission(intent.getData(),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
            sharedPref.edit().putString("drawer_header_path", intent.getData().toString()).commit();
            setDrawerHeaderBackground();
        }
    } else if (requestCode == 3) {
        Uri treeUri;
        if (responseCode == Activity.RESULT_OK) {
            // Get Uri from Storage Access Framework.
            treeUri = intent.getData();
            // Persist URI - this is required for verification of writability.
            if (treeUri != null)
                sharedPref.edit().putString("URI", treeUri.toString()).commit();
        } else {
            // If not confirmed SAF, or if still not writable, then revert settings.
            /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false, currentFolder);
                ||!FileUtil.isWritableNormalOrSaf(currentFolder)*/
            return;
        }

        // After confirmation, update stored value of folder.
        // Persist access permissions.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        switch (operation) {
        case DataUtils.DELETE://deletion
            new DeleteTask(null, mainActivity).execute((oparrayList));
            break;
        case DataUtils.COPY://copying
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }
            for (int i = 0; i < oparrayListList.size(); i++) {
                Intent intent1 = new Intent(con, CopyService.class);
                intent1.putExtra(CopyService.TAG_COPY_SOURCES, oparrayList.get(i));
                intent1.putExtra(CopyService.TAG_COPY_TARGET, oppatheList.get(i));
                ServiceWatcherUtil.runService(this, intent1);
            }
            break;
        case DataUtils.MOVE://moving
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }

            new MoveFiles(oparrayListList, ((MainFragment) getFragment().getTab()),
                    getFragment().getTab().getActivity(), OpenMode.FILE)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, oppatheList);
            break;
        case DataUtils.NEW_FOLDER://mkdir
            MainFragment ma1 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkDir(RootHelper.generateBaseFile(new File(oppathe), true), ma1);
            break;
        case DataUtils.RENAME:
            MainFragment ma2 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.rename(ma2.openMode, (oppathe), (oppathe1), mainActivity, BaseActivity.rootMode);
            ma2.updateList();
            break;
        case DataUtils.NEW_FILE:
            MainFragment ma3 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkFile(new HFile(OpenMode.FILE, oppathe), ma3);

            break;
        case DataUtils.EXTRACT:
            mainActivityHelper.extractFile(new File(oppathe));
            break;
        case DataUtils.COMPRESS:
            mainActivityHelper.compressFiles(new File(oppathe), oparrayList);
        }
        operation = -1;
    } else if (requestCode == REQUEST_CODE_SAF && responseCode == Activity.RESULT_OK) {
        // otg access
        sharedPref.edit().putString(KEY_PREF_OTG, intent.getData().toString()).apply();

        if (!isDrawerLocked)
            mDrawerLayout.closeDrawer(mDrawerLinear);
        else
            onDrawerClosed();
    } else if (requestCode == REQUEST_CODE_SAF && responseCode != Activity.RESULT_OK) {
        // otg access not provided
        pendingPath = null;
    }
}

From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java

private void markThreadAsRead() {
    new AsyncTask<Long, Void, Void>() {
        @Override/*from  ww  w.ja v  a  2  s.c  o m*/
        protected Void doInBackground(Long... params) {
            Context context = ConversationActivity.this;
            List<MarkedMessageInfo> messageIds = DatabaseFactory.getThreadDatabase(context).setRead(params[0],
                    false);

            MessageNotifier.updateNotification(context);
            MarkReadReceiver.process(context, messageIds);

            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, threadId);
}

From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java

private void markLastSeen() {
    new AsyncTask<Long, Void, Void>() {
        @Override//from   w ww .  j  a v  a 2  s .c  o m
        protected Void doInBackground(Long... params) {
            DatabaseFactory.getThreadDatabase(ConversationActivity.this).setLastSeen(params[0]);
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, threadId);
}

From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java

private ListenableFuture<Void> sendMediaMessage(final boolean forceSms, String body, SlideDeck slideDeck,
        List<Contact> contacts, List<LinkPreview> previews, final long expiresIn, final int subscriptionId,
        final boolean initiating) {
    if (!isDefaultSms && (!isSecureText || forceSms)) {
        showDefaultSmsPrompt();//from ww  w. j  ava  2 s  .com
        return new SettableFuture<>(null);
    }

    if (isSecureText && !forceSms) {
        Pair<String, Optional<Slide>> splitMessage = getSplitMessage(body,
                sendButton.getSelectedTransport().calculateCharacters(body).maxPrimaryMessageSize);
        body = splitMessage.first;

        if (splitMessage.second.isPresent()) {
            slideDeck.addSlide(splitMessage.second.get());
        }
    }

    OutgoingMediaMessage outgoingMessageCandidate = new OutgoingMediaMessage(recipient, slideDeck, body,
            System.currentTimeMillis(), subscriptionId, expiresIn, distributionType,
            inputPanel.getQuote().orNull(), contacts, previews);

    final SettableFuture<Void> future = new SettableFuture<>();
    final Context context = getApplicationContext();

    final OutgoingMediaMessage outgoingMessage;

    if (isSecureText && !forceSms) {
        outgoingMessage = new OutgoingSecureMediaMessage(outgoingMessageCandidate);
        ApplicationContext.getInstance(context).getTypingStatusSender().onTypingStopped(threadId);
    } else {
        outgoingMessage = outgoingMessageCandidate;
    }

    Permissions.with(this).request(Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS)
            .ifNecessary(!isSecureText || forceSms)
            .withPermanentDenialDialog(getString(
                    R.string.ConversationActivity_signal_needs_sms_permission_in_order_to_send_an_sms))
            .onAllGranted(() -> {
                inputPanel.clearQuote();
                attachmentManager.clear(glideRequests, false);
                silentlySetComposeText("");
                final long id = fragment.stageOutgoingMessage(outgoingMessage);

                new AsyncTask<Void, Void, Long>() {
                    @Override
                    protected Long doInBackground(Void... param) {
                        if (initiating) {
                            DatabaseFactory.getRecipientDatabase(context).setProfileSharing(recipient, true);
                        }

                        return MessageSender.send(context, outgoingMessage, threadId, forceSms,
                                () -> fragment.releaseOutgoingMessage(id));
                    }

                    @Override
                    protected void onPostExecute(Long result) {
                        sendComplete(result);
                        future.set(null);
                    }
                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }).onAnyDenied(() -> future.set(null)).execute();

    return future;
}