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.friedran.appengine.dashboard.client.AppEngineDashboardClient.java

/**
 * Send an authenticated GetApplications request asynchronously and return its results to the given callback.
 *//*from   w ww  . j a  v  a2  s .  c  o m*/
public void executeGetApplications(final PostExecuteCallback postGetApplicationsCallback) {
    new AuthenticatedRequestTask("https://appengine.google.com/",
            new AuthenticatedRequestTaskBackgroundCallback() {
                @Override
                public Bundle run(final HttpEntity httpResponse) {
                    Bundle result = new Bundle();
                    try {

                        mLastRetrievedApplications = AppEngineParserUtils
                                .getApplicationIDs(httpResponse.getContent());
                        result.putStringArrayList(KEY_APPLICATIONS, mLastRetrievedApplications);
                        result.putBoolean(KEY_RESULT, true);

                    } catch (IOException e) {
                        LogUtils.e("AppEngineDashboardClient", "Failed parsing the GetApplications response",
                                e);
                        result.putBoolean(KEY_RESULT, false);
                    }
                    return result;
                }
            }, postGetApplicationsCallback).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.dm.wallpaper.board.fragments.CategoriesFragment.java

public void getCategories() {
    if (mAsyncTask != null) {
        mAsyncTask.cancel(true);//www . j a  v  a  2s  . c  o  m
    }

    if (Database.get(getActivity()).getWallpapersCount() > 0) {
        mAsyncTask = new CategoriesLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return;
    }

    mAsyncTask = new CategoriesLoader().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.almalence.opencam.SavingService.java

@Override
public int onStartCommand(Intent intent, int flags, int startid) {
    long sessionID = intent.getLongExtra("sessionID", 0);
    if (sessionID == 0) {
        return START_NOT_STICKY;
    }/* w ww  .j  av a2s .c  o  m*/

    SavingTask task = new SavingTask();
    task.sessionID = sessionID;
    task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

    return START_NOT_STICKY;
}

From source file:com.github.gfx.android.orma.example.fragment.MainFragment.java

@Override
public void onStart() {
    super.onStart();

    // OrmaDatabase with migration steps
    // The current database schema version is 10 (= BuildConfig.VERSION_CODE)
    setupV1Database();/*from   w ww .j a v  a  2  s .c  o  m*/
    OrmaDatabase.Builder builder = OrmaDatabase.builder(getContext()).name(null);
    if (BuildConfig.FLAVOR.equals("encrypted")) {
        builder = builder.provider(new EncryptedDatabase.Provider(PASSWORD));
    }
    orma = builder.migrationStep(5, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 5, the table name was changed:
            helper.renameTable("todos", "Todo");
        }
    }).migrationStep(6, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 7, "note" was renamed to "title":
            helper.renameColumn("Todo", "note", "title");
        }
    }).migrationStep(7, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 7, "content", "done" were added:
            helper.execSQL("ALTER TABLE Todo ADD COLUMN content TEXT NULL");
            helper.execSQL("ALTER TABLE Todo ADD COLUMN done INTEGER NOT NULL DEFAULT 0");
        }
    }).migrationTraceListener((engine, format, args) -> binding.getRoot().post(() -> {
        logsAdapter.addAll(String.format(Locale.getDefault(), format, args));
        TraceListener.LOGCAT.onTrace(engine, format, args);
    })).build();

    AsyncTask.SERIAL_EXECUTOR.execute(() -> {
        try {
            Thread.sleep(1000);

            orma.migrate(); // may throws SQLiteConstraintException

            Log.d(TAG, "CRUD:start ------------------------");
            simpleCrud();
            Log.d(TAG, "rxCRUD:start ------------------------");
            rxCrud();
            Log.d(TAG, "CRUD:start ------------------------");
            associations();
            Log.d(TAG, "------------------------");
        } catch (final Exception e) {
            binding.getRoot().post(() -> {
                LargeLog.e(TAG, e);
                Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
            });
        }
    });
}

From source file:com.github.gfx.android.orma.example.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    setupViews();//from  w w  w.j  av  a2  s  .c  o m

    // OrmaDatabase with migration steps
    // The current database schema version is 10 (= BuildConfig.VERSION_CODE)
    setupV1Database();
    orma = OrmaDatabase.builder(this).name(DB_NAME).migrationStep(5, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 5, the table name was changed:
            helper.renameTable("todos", "Todo");
        }
    }).migrationStep(6, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 7, "note" was renamed to "title":
            helper.renameColumn("Todo", "note", "title");
        }
    }).migrationStep(7, new ManualStepMigration.ChangeStep() {
        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            // In schema version 7, "content", "done" were added:
            helper.execSQL("ALTER TABLE Todo ADD COLUMN content TEXT NULL");
            helper.execSQL("ALTER TABLE Todo ADD COLUMN done INTEGER NOT NULL DEFAULT 0");
        }
    }).migrationTraceListener(new TraceListener() {
        @Override
        public void onTrace(@NonNull final MigrationEngine engine, @NonNull final String format,
                @NonNull final Object[] args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    logsAdapter.addAll(String.format(Locale.getDefault(), format, args));
                    TraceListener.LOGCAT.onTrace(engine, format, args);
                }
            });
        }
    }).build();

    AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
        @Override
        public void run() {
            try {
                orma.migrate(); // may throws SQLiteConstraintException

                simpleCRUD();
                associations();
            } catch (final Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                    }
                });

                largeLogE(TAG, Log.getStackTraceString(e));
            }
        }
    });
}

From source file:com.tct.fw.ex.chips.DefaultPhotoManager.java

private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri,
        final PhotoManagerCallback callback) {
    final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() {
        @Override//w w  w  .ja  v  a2  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 (callback != null) {
                    callback.onPhotoBytesAsynchronouslyPopulated();
                }
            } else if (callback != null) {
                callback.onPhotoBytesAsyncLoadFailed();
            }
        }
    };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.friedran.appengine.dashboard.client.AppEngineDashboardClient.java

/**
 * Send an authenticated GetChart request asynchronously and return its results to the given callback.
 *//*from  w  w w . j  a v a 2 s .c  o m*/
public void executeGetChartUrl(String appID, int chartTypeID, int chartWindowID,
        final PostExecuteCallback postGetChartUrlCallback) {

    String url = String.format("https://appengine.google.com/dashboard/stats?app_id=s~%s&type=%d&window=%d",
            appID, chartTypeID, chartWindowID);

    new AuthenticatedRequestTask(url, new AuthenticatedRequestTaskBackgroundCallback() {
        @Override
        public Bundle run(final HttpEntity httpResponseEntity) {
            Bundle result = new Bundle();

            try {
                JSONObject jsonData = new JSONObject(EntityUtils.toString(httpResponseEntity));
                String chart_url = jsonData.getString("chart_url");

                result.putBoolean(KEY_RESULT, true);
                result.putString(KEY_CHART_URL, chart_url);

            } catch (Exception e) {
                LogUtils.e("AppEngineDashboardClient#onPostExecuteGetChartURL",
                        "Exception caught when tried to parse result", e);
                e.printStackTrace();
                result.putBoolean(KEY_RESULT, false);
            }

            return result;
        }
    }, postGetChartUrlCallback).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.dm.material.dashboard.candybar.activities.CandyBarSplashActivity.java

private void prepareCloudWallpapers(@NonNull Context context) {
    final String wallpaperUrl = getResources().getString(R.string.wallpaper_json);

    mPrepareCloudWallpapers = new AsyncTask<Void, Void, Boolean>() {
        @Override/*w  w  w.j  a va 2s  .c  o  m*/
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    if (WallpaperHelper.getWallpaperType(context) != WallpaperHelper.CLOUD_WALLPAPERS)
                        return true;

                    Database database = new Database(context);
                    if (database.getWallpapersCount() > 0)
                        return true;

                    URL url = new URL(wallpaperUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(15000);
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream stream = connection.getInputStream();
                        WallpaperJSON wallpapersJSON = LoganSquare.parse(stream, WallpaperJSON.class);
                        if (database.getWallpapersCount() > 0)
                            database.deleteWallpapers();
                        database.addWallpapers(wallpapersJSON);
                    }
                    return true;
                } catch (Exception e) {
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mPrepareCloudWallpapers = null;
        }
    }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

From source file:com.squareup.leakcanary.internal.DisplayLeakActivity.java

@SuppressLint("SetWorldReadable")
void shareHeapDump() {
    AnalyzedHeap visibleLeak = getVisibleLeak();
    final File heapDumpFile = visibleLeak.heapDump.heapDumpFile;
    AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
        @Override//from   ww  w  .ja va 2s  .  c o m
        public void run() {
            //noinspection ResultOfMethodCallIgnored
            heapDumpFile.setReadable(true, false);
            final Uri heapDumpUri = getUriForFile(getBaseContext(),
                    "com.squareup.leakcanary.fileprovider." + getApplication().getPackageName(), heapDumpFile);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    startShareIntentChooser(heapDumpUri);
                }
            });
        }
    });
}

From source file:com.podcatcher.deluxe.model.sync.gpodder.GpodderEpisodeMetadataSyncController.java

@Override
protected synchronized void syncEpisodeMetadata() {
    if (!syncRunning) {
        syncRunning = true;// w ww.  jav  a 2s  .  c  o  m

        new SyncEpisodeMetadataTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void) null);
    }
}