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.amaze.filemanager.fragments.Main.java

public void onSearchCompleted() {
    new AsyncTask<Void, Void, Void>() {
        @Override/*w  w w.  ja  va2s  .  c om*/
        protected Void doInBackground(Void... params) {
            Collections.sort(LIST_ELEMENTS, new FileListSorter(dsort, sortby, asc, ROOT_MODE));
            return null;
        }

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

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

private ListenableFuture<Boolean> initializeDraftFromDatabase() {
    SettableFuture<Boolean> future = new SettableFuture<>();

    new AsyncTask<Void, Void, List<Draft>>() {
        @Override/*from w  w  w  . j  a v  a 2s. co  m*/
        protected List<Draft> doInBackground(Void... params) {
            DraftDatabase draftDatabase = DatabaseFactory.getDraftDatabase(ConversationActivity.this);
            List<Draft> results = draftDatabase.getDrafts(threadId);

            draftDatabase.clearDrafts(threadId);

            return results;
        }

        @Override
        protected void onPostExecute(List<Draft> drafts) {
            if (drafts.isEmpty()) {
                future.set(false);
                updateToggleButtonState();
                return;
            }

            AtomicInteger draftsRemaining = new AtomicInteger(drafts.size());
            AtomicBoolean success = new AtomicBoolean(false);
            ListenableFuture.Listener<Boolean> listener = new AssertedSuccessListener<Boolean>() {
                @Override
                public void onSuccess(Boolean result) {
                    success.compareAndSet(false, result);

                    if (draftsRemaining.decrementAndGet() <= 0) {
                        future.set(success.get());
                    }
                }
            };

            for (Draft draft : drafts) {
                try {
                    switch (draft.getType()) {
                    case Draft.TEXT:
                        composeText.setText(draft.getValue());
                        listener.onSuccess(true);
                        break;
                    case Draft.LOCATION:
                        attachmentManager.setLocation(SignalPlace.deserialize(draft.getValue()),
                                getCurrentMediaConstraints()).addListener(listener);
                        break;
                    case Draft.IMAGE:
                        setMedia(Uri.parse(draft.getValue()), MediaType.IMAGE).addListener(listener);
                        break;
                    case Draft.AUDIO:
                        setMedia(Uri.parse(draft.getValue()), MediaType.AUDIO).addListener(listener);
                        break;
                    case Draft.VIDEO:
                        setMedia(Uri.parse(draft.getValue()), MediaType.VIDEO).addListener(listener);
                        break;
                    case Draft.QUOTE:
                        SettableFuture<Boolean> quoteResult = new SettableFuture<>();
                        new QuoteRestorationTask(draft.getValue(), quoteResult).execute();
                        quoteResult.addListener(listener);
                        break;
                    }
                } catch (IOException e) {
                    Log.w(TAG, e);
                }
            }

            updateToggleButtonState();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    return future;
}

From source file:me.willowcheng.makerthings.ui.OpenHABMainActivity.java

private void gcmRegisterBackground() {
    // We need settings
    if (mSettings == null)
        return;//  w w  w  .j  a v a2 s. com
    // We need remote URL, username and password, without them we can't connect to my.openHAB
    String remoteUrl = mSettings.getString(Constants.PREFERENCE_ALTURL, null);
    if (TextUtils.isEmpty(remoteUrl) || TextUtils.isEmpty(openHABUsername)
            || TextUtils.isEmpty(openHABPassword))
        return;
    // We need remote URL to be my.oh
    if (!remoteUrl.toLowerCase().startsWith("https://my.openhab.org"))
        return;
    mIsMyOpenHAB = true;
    // Finally, all sanity is done
    Crittercism.setUsername(openHABUsername);
    if (mGcm == null)
        mGcm = GoogleCloudMessaging.getInstance(getApplicationContext());
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            try {
                mRegId = mGcm.register(GCM_SENDER_ID);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String deviceModel = null;
                        try {
                            deviceModel = URLEncoder.encode(Build.MODEL, "UTF-8");
                            String deviceId = Settings.Secure.getString(getContentResolver(),
                                    Settings.Secure.ANDROID_ID);
                            String regUrl = "https://my.openhab.org/addAndroidRegistration?deviceId=" + deviceId
                                    + "&deviceModel=" + deviceModel + "&regId=" + mRegId;
                            mAsyncHttpClient.get(getApplicationContext(), regUrl,
                                    new AsyncHttpResponseHandler() {
                                        @Override
                                        public void onFailure(int statusCode, Header[] headers,
                                                byte[] responseBody, Throwable error) {
                                            Log.e(TAG, "GCM reg id error: " + error.getMessage());
                                            if (responseBody != null)
                                                Log.e(TAG, "Error response = " + new String(responseBody));
                                        }

                                        @Override
                                        public void onSuccess(int statusCode, Header[] headers,
                                                byte[] responseBody) {
                                            Log.d(TAG, "GCM reg id success");
                                        }
                                    });
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
            return mRegId;
        }

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

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

private ListenableFuture<Boolean> initializeSecurity(final boolean currentSecureText,
        final boolean currentIsDefaultSms) {
    final SettableFuture<Boolean> future = new SettableFuture<>();

    handleSecurityChange(currentSecureText || isPushGroupConversation(), currentIsDefaultSms);

    new AsyncTask<Recipient, Void, boolean[]>() {
        @Override//from ww  w .j  a  v  a 2s .c o  m
        protected boolean[] doInBackground(Recipient... params) {
            Context context = ConversationActivity.this;
            Recipient recipient = params[0];
            Log.i(TAG, "Resolving registered state...");
            RegisteredState registeredState;

            if (recipient.isPushGroupRecipient()) {
                Log.i(TAG, "Push group recipient...");
                registeredState = RegisteredState.REGISTERED;
            } else if (recipient.isResolving()) {
                Log.i(TAG, "Talking to DB directly.");
                registeredState = DatabaseFactory.getRecipientDatabase(ConversationActivity.this)
                        .isRegistered(recipient.getAddress());
            } else {
                Log.i(TAG, "Checking through resolved recipient");
                registeredState = recipient.resolve().getRegistered();
            }

            Log.i(TAG, "Resolved registered state: " + registeredState);
            boolean signalEnabled = TextSecurePreferences.isPushRegistered(context);

            if (registeredState == RegisteredState.UNKNOWN) {
                try {
                    Log.i(TAG, "Refreshing directory for user: " + recipient.getAddress().serialize());
                    registeredState = DirectoryHelper.refreshDirectoryFor(context, recipient);
                } catch (IOException e) {
                    Log.w(TAG, e);
                }
            }

            Log.i(TAG, "Returning registered state...");
            return new boolean[] { registeredState == RegisteredState.REGISTERED && signalEnabled,
                    Util.isDefaultSmsProvider(context) };
        }

        @Override
        protected void onPostExecute(boolean[] result) {
            if (result[0] != currentSecureText || result[1] != currentIsDefaultSms) {
                Log.i(TAG, "onPostExecute() handleSecurityChange: " + result[0] + " , " + result[1]);
                handleSecurityChange(result[0], result[1]);
            }
            future.set(true);
            onSecurityUpdated();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, recipient);

    return future;
}

From source file:com.filemanager.free.fragments.Main.java

public void onSearchCompleted() {
    if (!results) {
        LIST_ELEMENTS.clear();/*from   w  ww  . j ava 2 s  . c om*/
    }
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Collections.sort(LIST_ELEMENTS, new FileListSorter(dsort, sortby, asc, ROOT_MODE));
            return null;
        }

        @Override
        public void onPostExecute(Void c) {
            createViews(LIST_ELEMENTS, true, (CURRENT_PATH), openMode, true, !IS_LIST);
            pathname.setText(MAIN_ACTIVITY.getString(R.string.empty));
            mFullPath.setText(MAIN_ACTIVITY.getString(R.string.searchresults));
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MainActivity.showInterstitial();
                }
            }, 600);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.igniva.filemanager.fragments.Main.java

public void onSearchCompleted() {
    if (!results) {
        // no results were found
        LIST_ELEMENTS.clear();//from   w  ww  .  j av a2s .  co m
    }
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Collections.sort(LIST_ELEMENTS, new FileListSorter(dsort, sortby, asc, BaseActivity.rootMode));
            return null;
        }

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

From source file:com.taobao.weex.ui.component.list.template.WXRecyclerTemplateList.java

/**
 * copy cell async and save to cache/*from   ww w . j a va2  s  . c o  m*/
 * */
private void asyncLoadTemplateCache(final String template) {
    if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
        if (listData == null || listData.size() == 0) {
            return;
        }
        boolean firstScreenContains = false;
        for (int i = 0; i < listData.size(); i++) {
            if (template.equals(getTemplateKey(i))) {
                firstScreenContains = true;
                break;
            }
        }
        if (!firstScreenContains) {
            return;
        }
    }
    final WXCell source = mTemplateSources.get(template);
    if (source == null) {
        return;
    }
    TemplateCache cellCache = mTemplatesCache.get(template);
    if (cellCache == null) {
        cellCache = new TemplateCache();
        mTemplatesCache.put(template, cellCache);
    }
    if (cellCache.cells.size() > 0) {
        cellCache.isLoadIng = false;
        return;
    }
    if (cellCache.isLoadIng) {
        return;
    }
    cellCache.isLoadIng = true;
    AsyncTask<Void, Void, Void> preloadTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            TemplateCache cellCache = mTemplatesCache.get(template);
            if (cellCache == null || cellCache.cells == null) {
                return null;
            }
            while (cellCache.cells.size() < templateCacheSize) {
                WXCell component = (WXCell) copyCell(source);
                if (component == null) {
                    return null;
                }
                if (source.getInstance() == null || source.getInstance().isDestroy()) {
                    return null;
                }
                cellCache.cells.add(component);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (source.getInstance() == null || source.getInstance().isDestroy()) {
                return;
            }
            final TemplateCache cellCache = mTemplatesCache.get(template);
            if (cellCache == null) {
                return;
            }
            if (cellCache.cells == null || cellCache.cells.size() == 0) {
                cellCache.isLoadIng = false;
                return;
            }
            Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    if (source.getInstance() == null || source.getInstance().isDestroy()) {
                        return false;
                    }
                    ConcurrentLinkedQueue<WXCell> queue = cellCache.cells;
                    Iterator<WXCell> iterator = queue.iterator();
                    while (iterator.hasNext()) {
                        WXCell component = iterator.next();
                        if (component.isLazy()) {
                            doInitLazyCell(component, template, true);
                            return iterator.hasNext();
                        }
                    }
                    return false;
                }
            });
            cellCache.isLoadIng = false;
        }
    };
    preloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.entradahealth.entrada.android.app.personal.activities.job_list.JobListActivity.java

void launchSearchTask() {
    //get Generic ID
    Account acct = AndroidState.getInstance().getUserState().getCurrentAccount();
    state = AndroidState.getInstance().getUserState();
    reader = state.getProvider(acct);/*  w  ww  . ja  va  2s . c  o m*/

    //if(!BundleKeys.IS_FIRST_SYNC){
    GENERIC_PATIENT_ID = acct.getSetting(AccountSettingKeys.GENERIC_PATIENT_ID);
    if (GENERIC_PATIENT_ID != null && !GENERIC_PATIENT_ID.equals("")) {
        genericPatient = reader.getPatient(Long.parseLong(GENERIC_PATIENT_ID));
        if (genericPatient != null) {
            BundleKeys.LOCAL_MRN = genericPatient.medicalRecordNumber;
            important = Arrays.asList(BundleKeys.LOCAL_MRN);
        }
    }
    //}

    //      if (qchanged && !BundleKeys.ACC_EDITED) {
    Preconditions.checkNotNull(currentAccount, "current account is null");
    if (searchTask != null) {
        searchTask.cancel(true);
    }
    searchTask = new JobSearchTask(this, etSearch.getText().toString(), currentAccount, getFilter(),
            getComparator());

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