Example usage for android.os AsyncTask SERIAL_EXECUTOR

List of usage examples for android.os AsyncTask SERIAL_EXECUTOR

Introduction

In this page you can find the example usage for android.os AsyncTask SERIAL_EXECUTOR.

Prototype

Executor SERIAL_EXECUTOR

To view the source code for android.os AsyncTask SERIAL_EXECUTOR.

Click Source Link

Document

An Executor that executes tasks one at a time in serial order.

Usage

From source file:com.android.ex.chips.BaseRecipientAdapter.java

private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
    final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() {
        @Override/*from   w  w  w . ja  v a 2 s . co m*/
        protected byte[] doInBackground(Void... params) {
            // First try running a query. Images for local contacts are
            // loaded by sending a query to the ContactsProvider.
            final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null,
                    null, null);
            if (photoCursor != null) {
                try {
                    if (photoCursor.moveToFirst()) {
                        return photoCursor.getBlob(PhotoQuery.PHOTO);
                    }
                } finally {
                    photoCursor.close();
                }
            } else {
                // If the query fails, try streaming the URI directly.
                // For remote directory images, this URI resolves to the
                // directory provider and the images are loaded by sending
                // an openFile call to the provider.
                try {
                    InputStream is = mContentResolver.openInputStream(photoThumbnailUri);
                    if (is != null) {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            int size;
                            while ((size = is.read(buffer)) != -1) {
                                baos.write(buffer, 0, size);
                            }
                        } finally {
                            is.close();
                        }
                        return baos.toByteArray();
                    }
                } catch (IOException ex) {
                    // ignore
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(final byte[] photoBytes) {
            entry.setPhotoBytes(photoBytes);
            if (photoBytes != null) {
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                notifyDataSetChanged();
            }
        }
    };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.github.shareme.gwschips.library.BaseRecipientAdapter.java

private static void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri,
        final BaseAdapter adapter, final ContentResolver mContentResolver) {
    final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() {
        @Override//w w  w  .j  ava 2 s.c o  m
        protected byte[] doInBackground(Void... params) {
            // First try running a query. Images for local contacts are
            // loaded by sending a query to the ContactsProvider.
            final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null,
                    null, null);
            if (photoCursor != null) {
                try {
                    if (photoCursor.moveToFirst()) {
                        return photoCursor.getBlob(PhotoQuery.PHOTO);
                    }
                } finally {
                    photoCursor.close();
                }
            } else {
                // If the query fails, try streaming the URI directly.
                // For remote directory images, this URI resolves to the
                // directory provider and the images are loaded by sending
                // an openFile call to the provider.
                try {
                    InputStream is = mContentResolver.openInputStream(photoThumbnailUri);
                    if (is != null) {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            int size;
                            while ((size = is.read(buffer)) != -1) {
                                baos.write(buffer, 0, size);
                            }
                        } finally {
                            is.close();
                        }
                        return baos.toByteArray();
                    }
                } catch (IOException ex) {
                    // ignore
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(final byte[] photoBytes) {
            entry.setPhotoBytes(photoBytes);
            if (photoBytes != null) {
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                if (adapter != null)
                    adapter.notifyDataSetChanged();
            }
        }
    };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

private void saveNextTab() {
    if (mSaveTabTask != null)
        return;//from w  w  w .  j a v  a  2  s .c om
    if (!mTabsToSave.isEmpty()) {
        Tab tab = mTabsToSave.removeFirst();
        mSaveTabTask = new SaveTabTask(tab);
        mSaveTabTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    } else {
        saveTabListAsynchronously();
    }
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

/**
 * Kick off an AsyncTask to save the current list of Tabs.
 *///from  w w w . ja  v a  2s . c  o m
public void saveTabListAsynchronously() {
    if (mSaveListTask != null)
        mSaveListTask.cancel(true);
    mSaveListTask = new SaveListTask();
    mSaveListTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

/**
 * File mutations (e.g. saving & deleting) are explicitly serialized to ensure that they occur
 * in the correct order.//ww  w  .ja va  2  s . c o m
 *
 * @param file Name of file under the state directory to be deleted.
 */
private void deleteFileAsync(final String file) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            File stateFile = new File(getStateDirectory(), file);
            if (stateFile.exists()) {
                if (!stateFile.delete())
                    Log.e(TAG, "Failed to delete file: " + stateFile);

                // The merge isn't completely finished until the other TabPersistentStore's
                // metadata file is deleted.
                if (file.equals(mPersistencePolicy.getStateToBeMergedFileName())) {
                    mPersistencePolicy.setMergeInProgress(false);
                }
            }
            return null;
        }
    }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    // TODO(twellington): delete tab files using the thread pool rather than the serial
    // executor.
}

From source file:com.instiwork.RegistrationActivity.java

public void login_User(final String URL) {

    if (pDialogOut != null) {
        pDialogOut.show();//from w w w.  ja  v  a2 s.  c  o m
    }

    Logger.showMessage(TAG, "OutSide login_User" + URL);
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Logger.showMessage(TAG, "Inside login_User" + URL);
                    Logger.showMessage(TAG, response.toString());
                    Logger.showMessage(TAG, imgPath);

                    ll_image_selection.setEnabled(true);
                    txt_terms_conditions.setEnabled(true);
                    findViewById(R.id.footer).setEnabled(true);
                    findViewById(R.id.help_password).setEnabled(true);
                    findViewById(R.id.help_dob).setEnabled(true);
                    findViewById(R.id.help_license).setEnabled(true);

                    ll_license.setEnabled(true);
                    findViewById(R.id.loginBttn).setEnabled(true);
                    findViewById(R.id.fb_log).setEnabled(true);
                    dateOfBirth.setEnabled(true);
                    ll_image_selection.setClickable(true);
                    txt_terms_conditions.setClickable(true);
                    findViewById(R.id.footer).setClickable(true);
                    findViewById(R.id.help_password).setClickable(true);
                    findViewById(R.id.help_dob).setClickable(true);
                    findViewById(R.id.help_license).setClickable(true);

                    ll_license.setClickable(true);
                    findViewById(R.id.loginBttn).setClickable(true);
                    findViewById(R.id.fb_log).setClickable(true);
                    dateOfBirth.setClickable(true);

                    try {
                        InstiworkApplication.getInstance().setSelectedLicenseArray(null);
                        if (response.getString("status").equalsIgnoreCase("Success")) {

                            SharedPreferences.Editor edit = appSharedPref.edit();
                            edit.putString("USER_ID", response.getJSONObject("details").getString("userid"));
                            try {
                                edit.putString("CURRENCY_ID",
                                        response.getJSONObject("details").getString("currency_id"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            edit.commit();

                            InstiworkApplication.getInstance()
                                    .setUSER_ID(response.getJSONObject("details").getString("userid"));
                            InstiworkApplication.getInstance()
                                    .setUSER_NAME(response.getJSONObject("details").getString("name"));
                            InstiworkApplication.getInstance().setCOMPANY_NAME(
                                    response.getJSONObject("details").getString("companyname"));
                            InstiworkApplication.getInstance()
                                    .setUSER_EMAIL(response.getJSONObject("details").getString("email"));
                            InstiworkApplication.getInstance()
                                    .setMOBILE_NO(response.getJSONObject("details").getString("contact"));
                            try {
                                InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                        response.getJSONObject("details").getString("distance"));
                                InstiworkApplication.getInstance()
                                        .setUnit_user(response.getJSONObject("details").getString("unit"));
                            } catch (Exception e) {
                                try {
                                    InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                            response.getJSONObject("details").getString("distance_user"));
                                    InstiworkApplication.getInstance().setUnit_user(
                                            response.getJSONObject("details").getString("unit_user"));
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }

                            try {
                                InstiworkApplication.getInstance().setPush_status(
                                        response.getJSONObject("details").getString("push_status"));
                                InstiworkApplication.getInstance().setEmail_status(
                                        response.getJSONObject("details").getString("email_status"));
                                InstiworkApplication.getInstance().setText_status(
                                        response.getJSONObject("details").getString("text_status"));
                                InstiworkApplication.getInstance().setCountryid(
                                        response.getJSONObject("details").getString("country_id"));
                                InstiworkApplication.getInstance().setCurrency_id(
                                        response.getJSONObject("details").getString("currency_id"));
                                InstiworkApplication.getInstance().setCountry_name(
                                        response.getJSONObject("details").getString("country_name"));
                                InstiworkApplication.getInstance().setCountry_3_code(
                                        response.getJSONObject("details").getString("country_3_code"));
                                InstiworkApplication.getInstance().setCountry_2_code(
                                        response.getJSONObject("details").getString("country_2_code"));
                                InstiworkApplication.getInstance().setCurrency_code(
                                        response.getJSONObject("details").getString("currency_code"));
                                InstiworkApplication.getInstance().setCurrency_name(
                                        response.getJSONObject("details").getString("currency_name"));
                                InstiworkApplication.getInstance().setMember_since(
                                        response.getJSONObject("details").getString("member_since"));

                            } catch (Exception e) {
                                Logger.showMessage(TAG, "Extra Paremeter : " + e.toString());
                            }

                            try {
                                licenseLinkedList = new LinkedList<JSONObject>();
                                if (response.getJSONObject("details").getJSONArray("license").length() > 0) {
                                    for (int i = 0; i < response.getJSONObject("details")
                                            .getJSONArray("license").length(); i++) {
                                        licenseLinkedList.add(response.getJSONObject("details")
                                                .getJSONArray("license").getJSONObject(i));
                                    }
                                    InstiworkApplication.getInstance().setLicenseArray(licenseLinkedList);
                                } else {
                                    InstiworkApplication.getInstance().setLicenseArray(null);
                                }
                            } catch (Exception e) {
                                InstiworkApplication.getInstance().setLicenseArray(null);
                                Logger.showMessage(TAG, "license Exception" + e.toString());
                            }

                            try {
                                Map<String, Object> params = new HashMap<>();
                                params.put("action", "registration");
                                params.put("action_user_id", InstiworkApplication.getInstance().getUSER_ID());
                                params.put("action_user_name",
                                        InstiworkApplication.getInstance().getUSER_NAME());
                                params.put("action_device", "android");
                                AdWordsRemarketingReporter.reportWithConversionId(getApplicationContext(),
                                        getResources().getString(R.string.conversion_id), params);
                            } catch (Exception e) {
                                Logger.showMessage(TAG, "AdWords : " + e.toString());
                            }

                            if (imgPath.equalsIgnoreCase("")) {
                                if (pDialogOut != null) {
                                    pDialogOut.dismiss();
                                }
                                Toast.makeText(RegistrationActivity.this, "Registered successfully",
                                        Toast.LENGTH_SHORT).show();

                                InstiworkApplication.getInstance()
                                        .setUSER_IMG("" + R.drawable.placeholder_circuler);
                                Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(i);
                                finish();
                            } else {
                                if (pDialogOut != null) {
                                    pDialogOut.show();
                                }
                                String imgUploadUrl = InstiworkConstants.URL_DOMAIN
                                        + "Signup_ios/add_user_image?user_id="
                                        + response.getJSONObject("details").getString("userid");
                                (new UpdateAccountDetailsWithImage(imgPath, imgUploadUrl))
                                        .executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
                            }
                        } else {
                            pDialogOut.dismiss();

                            try {
                                displayMessage(response.getString("details"));
                            } catch (Exception e) {
                                e.printStackTrace();
                                try {
                                    displayMessage(response.getString("message"));
                                } catch (Exception ee) {
                                    ee.printStackTrace();
                                }
                            }

                            //Toast.makeText(RegistrationActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
                            //                                Snackbar.make(findViewById(android.R.id.content), response.getString("details"), Snackbar.LENGTH_LONG)
                            //                                        .setActionTextColor(Color.RED)
                            //                                        .show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Logger.showMessage(TAG, "Vollllllllll Error: " + error.getMessage());
                    pDialogOut.hide();

                    ll_image_selection.setEnabled(true);
                    txt_terms_conditions.setEnabled(true);
                    findViewById(R.id.footer).setEnabled(true);
                    findViewById(R.id.help_password).setEnabled(true);
                    findViewById(R.id.help_dob).setEnabled(true);
                    findViewById(R.id.help_license).setEnabled(true);

                    ll_license.setEnabled(true);
                    findViewById(R.id.loginBttn).setEnabled(true);
                    findViewById(R.id.fb_log).setEnabled(true);
                    dateOfBirth.setEnabled(true);
                    ll_image_selection.setClickable(true);
                    txt_terms_conditions.setClickable(true);
                    findViewById(R.id.footer).setClickable(true);
                    findViewById(R.id.help_password).setClickable(true);
                    findViewById(R.id.help_dob).setClickable(true);
                    findViewById(R.id.help_license).setClickable(true);

                    ll_license.setClickable(true);
                    findViewById(R.id.loginBttn).setClickable(true);
                    findViewById(R.id.fb_log).setClickable(true);
                    dateOfBirth.setClickable(true);

                    if (error instanceof NoConnectionError) {
                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                RegistrationActivity.this);
                        builder.setTitle("Instiwork");
                        builder.setMessage("You do not have internet connection!");
                        builder.setPositiveButton("retry", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();

                                pDialogOut.show();

                                ll_image_selection.setEnabled(false);
                                txt_terms_conditions.setEnabled(false);
                                findViewById(R.id.footer).setEnabled(false);
                                findViewById(R.id.help_password).setEnabled(false);
                                findViewById(R.id.help_dob).setEnabled(false);
                                findViewById(R.id.help_license).setEnabled(false);

                                ll_license.setEnabled(false);
                                findViewById(R.id.loginBttn).setEnabled(false);
                                findViewById(R.id.fb_log).setEnabled(false);
                                dateOfBirth.setEnabled(false);
                                ll_image_selection.setClickable(false);
                                txt_terms_conditions.setClickable(false);
                                findViewById(R.id.footer).setClickable(false);
                                findViewById(R.id.help_password).setClickable(false);
                                findViewById(R.id.help_dob).setClickable(false);
                                findViewById(R.id.help_license).setClickable(false);

                                ll_license.setClickable(false);
                                findViewById(R.id.loginBttn).setClickable(false);
                                findViewById(R.id.fb_log).setClickable(false);
                                dateOfBirth.setClickable(false);

                                login_User(URL);
                            }
                        });
                        builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });
                        builder.setCancelable(false);
                        builder.show();
                    } else {
                        String json = null;
                        NetworkResponse response = error.networkResponse;
                        if (response != null && response.data != null) {
                            json = new String(response.data);
                            json = trimMessage(json, "message");
                            if (json != null)
                                //                            displayMessage(json);
                                displayMessage(json + " Error Code : " + response.statusCode);
                        }
                    }
                }
            });
    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    InstiworkApplication.getInstance().addToRequestQueue(jsonObjReq);
}