use of android.os.AsyncTask in project android by nextcloud.
the class OCFileListFragment method onMessageEvent.
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(final SearchEvent event) {
searchFragment = true;
setEmptyListLoadingMessage();
mAdapter.setData(new ArrayList<>(), SearchType.NO_SEARCH, mContainerActivity.getStorageManager(), mFile);
setFabEnabled(false);
if (event.getUnsetType().equals(SearchEvent.UnsetType.UNSET_BOTTOM_NAV_BAR)) {
unsetAllMenuItems(false);
} else if (event.getUnsetType().equals(SearchEvent.UnsetType.UNSET_DRAWER)) {
unsetAllMenuItems(true);
}
if (bottomNavigationView != null && searchEvent != null) {
switch(currentSearchType) {
case FAVORITE_SEARCH:
DisplayUtils.setBottomBarItem(bottomNavigationView, R.id.nav_bar_favorites);
break;
case PHOTO_SEARCH:
DisplayUtils.setBottomBarItem(bottomNavigationView, R.id.nav_bar_photos);
break;
default:
DisplayUtils.setBottomBarItem(bottomNavigationView, -1);
break;
}
}
Runnable switchViewsRunnable = new Runnable() {
@Override
public void run() {
if (isGridViewPreferred(mFile) && !isGridEnabled()) {
switchToGridView();
} else if (!isGridViewPreferred(mFile) && isGridEnabled()) {
switchToListView();
}
}
};
if (currentSearchType.equals(SearchType.PHOTO_SEARCH)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
switchToGridView();
}
});
} else if (currentSearchType.equals(SearchType.NO_SEARCH) || currentSearchType.equals(SearchType.REGULAR_FILTER)) {
new Handler(Looper.getMainLooper()).post(switchViewsRunnable);
} else {
new Handler(Looper.getMainLooper()).post(switchViewsRunnable);
}
final RemoteOperation remoteOperation;
if (!currentSearchType.equals(SearchType.SHARED_FILTER)) {
boolean searchOnlyFolders = false;
if (getArguments() != null && getArguments().getBoolean(ARG_SEARCH_ONLY_FOLDER, false)) {
searchOnlyFolders = true;
}
remoteOperation = new SearchOperation(event.getSearchQuery(), event.getSearchType(), searchOnlyFolders);
} else {
remoteOperation = new GetRemoteSharesOperation();
}
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
remoteOperationAsyncTask = new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
if (getContext() != null && !isCancelled()) {
RemoteOperationResult remoteOperationResult = remoteOperation.execute(currentAccount, getContext());
FileDataStorageManager storageManager = null;
if (mContainerActivity != null && mContainerActivity.getStorageManager() != null) {
storageManager = mContainerActivity.getStorageManager();
}
if (remoteOperationResult.isSuccess() && remoteOperationResult.getData() != null && !isCancelled() && searchFragment) {
if (remoteOperationResult.getData() == null || remoteOperationResult.getData().size() == 0) {
setEmptyView(event);
} else {
mAdapter.setData(remoteOperationResult.getData(), currentSearchType, storageManager, mFile);
}
final ToolbarActivity fileDisplayActivity = (ToolbarActivity) getActivity();
if (fileDisplayActivity != null) {
fileDisplayActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (fileDisplayActivity != null) {
fileDisplayActivity.setIndeterminate(false);
}
}
});
}
}
return remoteOperationResult.isSuccess();
} else {
return false;
}
}
@Override
protected void onPostExecute(Object o) {
if (!isCancelled()) {
mAdapter.notifyDataSetChanged();
}
}
};
remoteOperationAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, true);
}
use of android.os.AsyncTask in project AndroidChromium by JackyAndroid.
the class SigninHelper method validateAccountSettings.
public void validateAccountSettings(boolean accountsChanged) {
// Ensure System accounts have been seeded.
mAccountTrackerService.checkAndSeedSystemAccounts();
if (!accountsChanged) {
mAccountTrackerService.validateSystemAccounts();
}
Account syncAccount = mChromeSigninController.getSignedInUser();
if (syncAccount == null) {
ChromePreferenceManager chromePreferenceManager = ChromePreferenceManager.getInstance(mContext);
if (chromePreferenceManager.getShowSigninPromo())
return;
// Never shows a signin promo if user has manually disconnected.
String lastSyncAccountName = PrefServiceBridge.getInstance().getSyncLastAccountName();
if (lastSyncAccountName != null && !lastSyncAccountName.isEmpty())
return;
if (!chromePreferenceManager.getSigninPromoShown() && AccountManagerHelper.get(mContext).getGoogleAccountNames().size() > 0) {
chromePreferenceManager.setShowSigninPromo(true);
}
return;
}
String renamedAccount = getNewSignedInAccountName(mContext);
if (accountsChanged && renamedAccount != null) {
handleAccountRename(ChromeSigninController.get(mContext).getSignedInAccountName(), renamedAccount);
return;
}
// Always check for account deleted.
if (!accountExists(mContext, syncAccount)) {
// It is possible that Chrome got to this point without account
// rename notification. Let us signout before doing a rename.
// updateAccountRenameData(mContext, new SystemAccountChangeEventChecker());
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
updateAccountRenameData(mContext, new SystemAccountChangeEventChecker());
return null;
}
@Override
protected void onPostExecute(Void result) {
String renamedAccount = getNewSignedInAccountName(mContext);
if (renamedAccount == null) {
mSigninManager.signOut();
} else {
validateAccountSettings(true);
}
}
};
task.execute();
return;
}
if (accountsChanged) {
// Account details have changed so inform the token service that credentials
// should now be available.
mOAuth2TokenService.validateAccounts(mContext, false);
}
if (mProfileSyncService != null && AndroidSyncSettings.isSyncEnabled(mContext)) {
if (mProfileSyncService.isFirstSetupComplete()) {
if (accountsChanged) {
// Nudge the syncer to ensure it does a full sync.
InvalidationServiceFactory.getForProfile(Profile.getLastUsedProfile()).requestSyncFromNativeChromeForAllTypes();
}
} else {
// We should have set up sync but for some reason it's not enabled. Tell the sync
// engine to start.
mProfileSyncService.requestStart();
}
}
}
use of android.os.AsyncTask in project AndroidChromium by JackyAndroid.
the class PartnerBrowserCustomizations method initializeAsync.
/**
* Constructs an async task that reads PartnerBrowserCustomization provider.
*
* @param context The current application context.
* @param timeoutMs If initializing takes more than this time, cancels it. The unit is ms.
*/
public static void initializeAsync(final Context context, long timeoutMs) {
sIsInitialized = false;
// Setup an initializing async task.
final AsyncTask<Void, Void, Void> initializeAsyncTask = new AsyncTask<Void, Void, Void>() {
private boolean mDisablePartnerBookmarksShim;
private boolean mHomepageUriChanged;
private void refreshHomepage() {
try {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(buildQueryUri(PARTNER_HOMEPAGE_PATH), null, null, null, null);
if (cursor != null && cursor.moveToFirst() && cursor.getColumnCount() == 1 && !isCancelled()) {
if (TextUtils.isEmpty(sHomepage) || !sHomepage.equals(cursor.getString(0))) {
mHomepageUriChanged = true;
}
sHomepage = cursor.getString(0);
}
if (cursor != null)
cursor.close();
} catch (Exception e) {
Log.w(TAG, "Partner homepage provider URL read failed : ", e);
}
}
private void refreshIncognitoModeDisabled() {
try {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(buildQueryUri(PARTNER_DISABLE_INCOGNITO_MODE_PATH), null, null, null, null);
if (cursor != null && cursor.moveToFirst() && cursor.getColumnCount() == 1 && !isCancelled()) {
sIncognitoModeDisabled = cursor.getInt(0) == 1;
}
if (cursor != null)
cursor.close();
} catch (Exception e) {
Log.w(TAG, "Partner disable incognito mode read failed : ", e);
}
}
private void refreshBookmarksEditingDisabled() {
try {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(buildQueryUri(PARTNER_DISABLE_BOOKMARKS_EDITING_PATH), null, null, null, null);
if (cursor != null && cursor.moveToFirst() && cursor.getColumnCount() == 1 && !isCancelled()) {
boolean bookmarksEditingDisabled = cursor.getInt(0) == 1;
if (bookmarksEditingDisabled != sBookmarksEditingDisabled) {
mDisablePartnerBookmarksShim = true;
}
sBookmarksEditingDisabled = bookmarksEditingDisabled;
}
if (cursor != null)
cursor.close();
} catch (Exception e) {
Log.w(TAG, "Partner disable bookmarks editing read failed : ", e);
}
}
@Override
protected Void doInBackground(Void... params) {
try {
ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider(sProviderAuthority, 0);
if (providerInfo == null)
return null;
if ((providerInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 && !sIgnoreBrowserProviderSystemPackageCheck) {
Log.w("TAG", "Browser Cutomizations content provider package, " + providerInfo.packageName + ", is not a system package. " + "This could be a malicious attepment from a third party app, " + "so skip reading the browser content provider.");
return null;
}
if (isCancelled())
return null;
refreshIncognitoModeDisabled();
if (isCancelled())
return null;
refreshBookmarksEditingDisabled();
if (isCancelled())
return null;
refreshHomepage();
} catch (Exception e) {
Log.w(TAG, "Fetching partner customizations failed", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
onFinalized();
}
@Override
protected void onCancelled(Void result) {
onFinalized();
}
private void onFinalized() {
sIsInitialized = true;
for (Runnable callback : sInitializeAsyncCallbacks) {
callback.run();
}
sInitializeAsyncCallbacks.clear();
if (mHomepageUriChanged) {
HomepageManager.getInstance(context).notifyHomepageUpdated();
}
// Disable partner bookmarks editing if necessary.
if (mDisablePartnerBookmarksShim) {
PartnerBookmarksReader.disablePartnerBookmarksEditing();
}
}
};
initializeAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Cancel the initialization if it reaches timeout.
ThreadUtils.postOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
initializeAsyncTask.cancel(true);
}
}, timeoutMs);
}
use of android.os.AsyncTask in project android_frameworks_base by crdroidandroid.
the class ContentProvider method openPipeHelper.
/**
* A helper function for implementing {@link #openTypedAssetFile}, for
* creating a data pipe and background thread allowing you to stream
* generated data back to the client. This function returns a new
* ParcelFileDescriptor that should be returned to the caller (the caller
* is responsible for closing it).
*
* @param uri The URI whose data is to be written.
* @param mimeType The desired type of data to be written.
* @param opts Options supplied by caller.
* @param args Your own custom arguments.
* @param func Interface implementing the function that will actually
* stream the data.
* @return Returns a new ParcelFileDescriptor holding the read side of
* the pipe. This should be returned to the caller for reading; the caller
* is responsible for closing it when done.
*/
@NonNull
public <T> ParcelFileDescriptor openPipeHelper(@NonNull final Uri uri, @NonNull final String mimeType, @Nullable final Bundle opts, @Nullable final T args, @NonNull final PipeDataWriter<T> func) throws FileNotFoundException {
try {
final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... params) {
func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
try {
fds[1].close();
} catch (IOException e) {
Log.w(TAG, "Failure closing pipe", e);
}
return null;
}
};
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[]) null);
return fds[0];
} catch (IOException e) {
throw new FileNotFoundException("failure making pipe");
}
}
use of android.os.AsyncTask in project android_frameworks_base by crdroidandroid.
the class WallpaperCropActivity method setCropViewTileSource.
public void setCropViewTileSource(final BitmapRegionTileSource.BitmapSource bitmapSource, final boolean touchEnabled, final boolean moveToLeft, final Runnable postExecute) {
final Context context = WallpaperCropActivity.this;
final View progressView = findViewById(R.id.loading);
final AsyncTask<Void, Void, Void> loadBitmapTask = new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... args) {
if (!isCancelled()) {
try {
bitmapSource.loadInBackground();
} catch (SecurityException securityException) {
if (isDestroyed()) {
// Temporarily granted permissions are revoked when the activity
// finishes, potentially resulting in a SecurityException here.
// Even though {@link #isDestroyed} might also return true in different
// situations where the configuration changes, we are fine with
// catching these cases here as well.
cancel(false);
} else {
// otherwise it had a different cause and we throw it further
throw securityException;
}
}
}
return null;
}
protected void onPostExecute(Void arg) {
if (!isCancelled()) {
progressView.setVisibility(View.INVISIBLE);
if (bitmapSource.getLoadingState() == BitmapSource.State.LOADED) {
mCropView.setTileSource(new BitmapRegionTileSource(context, bitmapSource), null);
mCropView.setTouchEnabled(touchEnabled);
if (moveToLeft) {
mCropView.moveToLeft();
}
}
}
if (postExecute != null) {
postExecute.run();
}
}
};
// We don't want to show the spinner every time we load an image, because that would be
// annoying; instead, only start showing the spinner if loading the image has taken
// longer than 1 sec (ie 1000 ms)
progressView.postDelayed(new Runnable() {
public void run() {
if (loadBitmapTask.getStatus() != AsyncTask.Status.FINISHED) {
progressView.setVisibility(View.VISIBLE);
}
}
}, 1000);
loadBitmapTask.execute();
}
Aggregations