Search in sources :

Example 26 with AsyncTask

use of android.os.AsyncTask in project android_frameworks_base by crdroidandroid.

the class LockscreenWallpaper method run.

@Override
public void run() {
    if (mLoader != null) {
        mLoader.cancel(false);
    }
    final int currentUser = mCurrentUserId;
    final UserHandle selectedUser = mSelectedUser;
    mLoader = new AsyncTask<Void, Void, LoaderResult>() {

        @Override
        protected LoaderResult doInBackground(Void... params) {
            return loadBitmap(currentUser, selectedUser);
        }

        @Override
        protected void onPostExecute(LoaderResult result) {
            super.onPostExecute(result);
            if (isCancelled()) {
                return;
            }
            if (result.success) {
                mCached = true;
                mCache = result.bitmap;
                mUpdateMonitor.setHasLockscreenWallpaper(result.bitmap != null);
                mBar.updateMediaMetaData(true, /* metaDataChanged */
                true);
            }
            mLoader = null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
Also used : UserHandle(android.os.UserHandle) AsyncTask(android.os.AsyncTask)

Example 27 with AsyncTask

use of android.os.AsyncTask in project android_frameworks_base by crdroidandroid.

the class LockPatternChecker method checkPattern.

/**
     * Checks a pattern asynchronously.
     *
     * @param utils The LockPatternUtils instance to use.
     * @param pattern The pattern to check.
     * @param userId The user to check against the pattern.
     * @param callback The callback to be invoked with the check result.
     */
public static AsyncTask<?, ?, ?> checkPattern(final LockPatternUtils utils, final List<LockPatternView.Cell> pattern, final int userId, final OnCheckCallback callback) {
    AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

        private int mThrottleTimeout;

        private List<LockPatternView.Cell> patternCopy;

        @Override
        protected void onPreExecute() {
            // Make a copy of the pattern to prevent race conditions.
            // No need to clone the individual cells because they are immutable.
            patternCopy = new ArrayList(pattern);
        }

        @Override
        protected Boolean doInBackground(Void... args) {
            try {
                return utils.checkPattern(patternCopy, userId, callback::onEarlyMatched);
            } catch (RequestThrottledException ex) {
                mThrottleTimeout = ex.getTimeoutMs();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            callback.onChecked(result, mThrottleTimeout);
        }
    };
    task.execute();
    return task;
}
Also used : AsyncTask(android.os.AsyncTask) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) RequestThrottledException(com.android.internal.widget.LockPatternUtils.RequestThrottledException)

Example 28 with AsyncTask

use of android.os.AsyncTask in project android_frameworks_base by AOSPA.

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 29 with AsyncTask

use of android.os.AsyncTask in project android_packages_apps_Settings by LineageOS.

the class NotificationSoundPreference method updateRingtoneName.

private void updateRingtoneName(final Uri uri) {
    AsyncTask ringtoneNameTask = new AsyncTask<Object, Void, CharSequence>() {

        @Override
        protected CharSequence doInBackground(Object... params) {
            if (uri == null) {
                return getContext().getString(com.android.internal.R.string.ringtone_silent);
            } else if (RingtoneManager.isDefault(uri)) {
                return getContext().getString(R.string.notification_sound_default);
            } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())) {
                return getContext().getString(R.string.notification_unknown_sound_title);
            } else {
                return Ringtone.getTitle(getContext(), uri, false, /* followSettingsUri */
                true);
            }
        }

        @Override
        protected void onPostExecute(CharSequence name) {
            setSummary(name);
        }
    };
    ringtoneNameTask.execute();
}
Also used : AsyncTask(android.os.AsyncTask)

Example 30 with AsyncTask

use of android.os.AsyncTask in project Slide by ccrama.

the class MainActivity method doSubOnlyStuff.

public void doSubOnlyStuff(final Subreddit subreddit) {
    findViewById(R.id.loader).setVisibility(View.GONE);
    if (subreddit.getSubredditType() != null) {
        canSubmit = !subreddit.getSubredditType().equals("RESTRICTED");
    } else {
        canSubmit = true;
    }
    if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
        findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
        final String text = subreddit.getDataNode().get("description_html").asText().trim();
        setViews(text, subreddit.getDisplayName(), sidebarBody, sidebarOverflow);
        // get all subs that have Notifications enabled
        ArrayList<String> rawSubs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
        HashMap<String, Integer> subThresholds = new HashMap<>();
        for (String s : rawSubs) {
            try {
                String[] split = s.split(":");
                subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
            } catch (Exception ignored) {
            // do nothing
            }
        }
        // whether or not this subreddit was in the keySet
        boolean isNotified = subThresholds.keySet().contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
        ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
    } else {
        findViewById(R.id.sidebar_text).setVisibility(View.GONE);
    }
    {
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    new AsyncTask<Void, Void, Void>() {

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(MainActivity.this).title(getString(R.string.multi_add_to, subreddit.getDisplayName())).items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[multis.size()])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        View view = s.getView();
                                                        TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                        tv.setTextColor(Color.WHITE);
                                                        s.show();
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, new View.OnClickListener() {

                                                                    @Override
                                                                    public void onClick(View v) {
                                                                    }
                                                                }).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
    }
    {
        final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
        assert notifyStateCheckBox != null;
        notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    final String sub = subreddit.getDisplayName();
                    if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new MaterialDialog.Builder(MainActivity.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        ArrayList<String> subs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                        subs.add(sub + ":" + text);
                                        Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, Reddit.arrayToString(subs)).commit();
                                        return true;
                                    }
                                }).cancelable(false).show();
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                notifyStateCheckBox.setChecked(false);
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                notifyStateCheckBox.setChecked(false);
                            }
                        }).show();
                    } else {
                        notifyStateCheckBox.setChecked(false);
                        Toast.makeText(MainActivity.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent cancelIntent = new Intent(MainActivity.this, CancelSubNotifs.class);
                    cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                    startActivity(cancelIntent);
                }
            }
        });
    }
    {
        final TextView subscribe = (TextView) findViewById(R.id.subscribe);
        currentlySubbed = (!Authentication.isLoggedIn && usedArray.contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || subreddit.isUserSubscriber();
        doSubscribeButtonText(currentlySubbed, subscribe);
        assert subscribe != null;
        subscribe.setOnClickListener(new View.OnClickListener() {

            private void doSubscribe() {
                if (Authentication.isLoggedIn) {
                    new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new AsyncTask<Void, Void, Boolean>() {

                                @Override
                                public void onPostExecute(Boolean success) {
                                    if (!success) {
                                        // If subreddit was removed from account or not
                                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeSubscription(subreddit, // Force add the subscription
                                                true);
                                                Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_LONG);
                                                View view = s.getView();
                                                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                tv.setTextColor(Color.WHITE);
                                                s.show();
                                            }
                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }).setCancelable(false).show();
                                    } else {
                                        changeSubscription(subreddit, true);
                                    }
                                }

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).subscribe(subreddit);
                                    } catch (NetworkException e) {
                                        // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                        return false;
                                    }
                                    return true;
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).setNeutralButton(R.string.btn_add_to_sublist, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            changeSubscription(subreddit, // Force add the subscription
                            true);
                            Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_LONG);
                            View view = s.getView();
                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                            tv.setTextColor(Color.WHITE);
                            s.show();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, true);
                }
            }

            private void doUnsubscribe() {
                if (Authentication.didOnline) {
                    new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubsribe, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new AsyncTask<Void, Void, Boolean>() {

                                @Override
                                public void onPostExecute(Boolean success) {
                                    if (!success) {
                                        // If subreddit was removed from account or not
                                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeSubscription(subreddit, // Force add the subscription
                                                false);
                                                Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_LONG);
                                                View view = s.getView();
                                                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                tv.setTextColor(Color.WHITE);
                                                s.show();
                                            }
                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }).setCancelable(false).show();
                                    } else {
                                        changeSubscription(subreddit, false);
                                    }
                                }

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                                    } catch (NetworkException e) {
                                        // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                        return false;
                                    }
                                    return true;
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).setNeutralButton(R.string.just_unsub, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            changeSubscription(subreddit, // Force add the subscription
                            false);
                            Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_LONG);
                            View view = s.getView();
                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                            tv.setTextColor(Color.WHITE);
                            s.show();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, false);
                }
            }

            @Override
            public void onClick(View v) {
                if (!currentlySubbed) {
                    doSubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                } else {
                    doUnsubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                }
            }
        });
    }
    if (!subreddit.getPublicDescription().isEmpty()) {
        findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
        setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
    } else {
        findViewById(R.id.sub_title).setVisibility(View.GONE);
    }
    ((ImageView) findViewById(R.id.subimage)).setImageResource(0);
    if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
        findViewById(R.id.subimage).setVisibility(View.VISIBLE);
        ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
    } else {
        findViewById(R.id.subimage).setVisibility(View.GONE);
    }
    ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
    findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
    ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
    findViewById(R.id.active_users).setVisibility(View.VISIBLE);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) AccountManager(net.dean.jraw.managers.AccountManager) Snackbar(android.support.design.widget.Snackbar) DialogInterface(android.content.DialogInterface) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) NetworkException(net.dean.jraw.http.NetworkException) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) CardView(android.support.v7.widget.CardView) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) Point(android.graphics.Point) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) CompoundButton(android.widget.CompoundButton) ApiException(net.dean.jraw.ApiException)

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