Search in sources :

Example 21 with AsyncTask

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);
}
Also used : ToolbarActivity(com.owncloud.android.ui.activity.ToolbarActivity) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) SearchOperation(com.owncloud.android.lib.resources.files.SearchOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) AsyncTask(android.os.AsyncTask) Handler(android.os.Handler) GetRemoteSharesOperation(com.owncloud.android.lib.resources.shares.GetRemoteSharesOperation) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) Subscribe(org.greenrobot.eventbus.Subscribe)

Example 22 with AsyncTask

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();
        }
    }
}
Also used : Account(android.accounts.Account) AsyncTask(android.os.AsyncTask) ChromePreferenceManager(org.chromium.chrome.browser.preferences.ChromePreferenceManager)

Example 23 with AsyncTask

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);
}
Also used : ProviderInfo(android.content.pm.ProviderInfo) AsyncTask(android.os.AsyncTask) Cursor(android.database.Cursor) ContentResolver(android.content.ContentResolver)

Example 24 with AsyncTask

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");
    }
}
Also used : ParcelFileDescriptor(android.os.ParcelFileDescriptor) AsyncTask(android.os.AsyncTask) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) NonNull(android.annotation.NonNull)

Example 25 with AsyncTask

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();
}
Also used : Context(android.content.Context) AsyncTask(android.os.AsyncTask) View(android.view.View) BitmapRegionTileSource(com.android.photos.BitmapRegionTileSource)

Aggregations

AsyncTask (android.os.AsyncTask)395 IOException (java.io.IOException)188 InputStream (java.io.InputStream)159 URL (java.net.URL)159 HttpURLConnection (java.net.HttpURLConnection)158 ExecutionException (java.util.concurrent.ExecutionException)158 Gson (com.google.gson.Gson)155 Message (com.remswork.project.alice.model.support.Message)153 GradingFactorException (com.remswork.project.alice.exception.GradingFactorException)102 ArrayList (java.util.ArrayList)93 View (android.view.View)54 Intent (android.content.Intent)52 TextView (android.widget.TextView)52 JSONException (org.json.JSONException)51 JSONArray (org.json.JSONArray)50 DialogInterface (android.content.DialogInterface)40 OutputStream (java.io.OutputStream)37 BufferedWriter (java.io.BufferedWriter)35 OutputStreamWriter (java.io.OutputStreamWriter)35 ImageView (android.widget.ImageView)33