Search in sources :

Example 51 with AsyncTask

use of android.os.AsyncTask in project AmazeFileManager by TeamAmaze.

the class GeneralDialogCreation method deleteFilesDialog.

@SuppressWarnings("ConstantConditions")
public static void deleteFilesDialog(final Context c, final ArrayList<LayoutElementParcelable> layoutElements, final MainActivity mainActivity, final List<LayoutElementParcelable> positions, AppTheme appTheme) {
    final ArrayList<HybridFileParcelable> itemsToDelete = new ArrayList<>();
    int accentColor = mainActivity.getColorPreference().getColor(ColorUsage.ACCENT);
    // Build dialog with custom view layout and accent color.
    MaterialDialog dialog = new MaterialDialog.Builder(c).title(c.getString(R.string.dialog_delete_title)).customView(R.layout.dialog_delete, true).theme(appTheme.getMaterialDialogTheme()).negativeText(c.getString(R.string.cancel).toUpperCase()).positiveText(c.getString(R.string.delete).toUpperCase()).positiveColor(accentColor).negativeColor(accentColor).onPositive((dialog1, which) -> {
        Toast.makeText(c, c.getString(R.string.deleting), Toast.LENGTH_SHORT).show();
        mainActivity.mainActivityHelper.deleteFiles(itemsToDelete);
    }).build();
    // Get views from custom layout to set text values.
    final TextView categoryDirectories = (TextView) dialog.getCustomView().findViewById(R.id.category_directories);
    final TextView categoryFiles = (TextView) dialog.getCustomView().findViewById(R.id.category_files);
    final TextView listDirectories = (TextView) dialog.getCustomView().findViewById(R.id.list_directories);
    final TextView listFiles = (TextView) dialog.getCustomView().findViewById(R.id.list_files);
    final TextView total = (TextView) dialog.getCustomView().findViewById(R.id.total);
    // Parse items to delete.
    new AsyncTask<Void, Object, Void>() {

        long sizeTotal = 0;

        StringBuilder files = new StringBuilder();

        StringBuilder directories = new StringBuilder();

        int counterDirectories = 0;

        int counterFiles = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            listFiles.setText(c.getString(R.string.loading));
            listDirectories.setText(c.getString(R.string.loading));
            total.setText(c.getString(R.string.loading));
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < positions.size(); i++) {
                final LayoutElementParcelable layoutElement = positions.get(i);
                itemsToDelete.add(layoutElement.generateBaseFile());
                // Build list of directories to delete.
                if (layoutElement.isDirectory) {
                    // Don't add newline between category and list.
                    if (counterDirectories != 0) {
                        directories.append("\n");
                    }
                    long sizeDirectory = layoutElement.generateBaseFile().folderSize(c);
                    directories.append(++counterDirectories).append(". ").append(layoutElement.title).append(" (").append(Formatter.formatFileSize(c, sizeDirectory)).append(")");
                    sizeTotal += sizeDirectory;
                // Build list of files to delete.
                } else {
                    // Don't add newline between category and list.
                    if (counterFiles != 0) {
                        files.append("\n");
                    }
                    files.append(++counterFiles).append(". ").append(layoutElement.title).append(" (").append(layoutElement.size).append(")");
                    sizeTotal += layoutElement.longSize;
                }
                publishProgress(sizeTotal, counterFiles, counterDirectories, files, directories);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object... result) {
            super.onProgressUpdate(result);
            int tempCounterFiles = (int) result[1];
            int tempCounterDirectories = (int) result[2];
            long tempSizeTotal = (long) result[0];
            StringBuilder tempFilesStringBuilder = (StringBuilder) result[3];
            StringBuilder tempDirectoriesStringBuilder = (StringBuilder) result[4];
            updateViews(tempSizeTotal, tempFilesStringBuilder, tempDirectoriesStringBuilder, tempCounterFiles, tempCounterDirectories);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            updateViews(sizeTotal, files, directories, counterFiles, counterDirectories);
        }

        private void updateViews(long tempSizeTotal, StringBuilder filesStringBuilder, StringBuilder directoriesStringBuilder, int... values) {
            int tempCounterFiles = values[0];
            int tempCounterDirectories = values[1];
            // Hide category and list for directories when zero.
            if (tempCounterDirectories == 0) {
                if (tempCounterDirectories == 0) {
                    categoryDirectories.setVisibility(View.GONE);
                    listDirectories.setVisibility(View.GONE);
                }
            // Hide category and list for files when zero.
            }
            if (tempCounterFiles == 0) {
                categoryFiles.setVisibility(View.GONE);
                listFiles.setVisibility(View.GONE);
            }
            if (tempCounterDirectories != 0 || tempCounterFiles != 0) {
                listDirectories.setText(directoriesStringBuilder);
                if (listDirectories.getVisibility() != View.VISIBLE && tempCounterDirectories != 0)
                    listDirectories.setVisibility(View.VISIBLE);
                listFiles.setText(filesStringBuilder);
                if (listFiles.getVisibility() != View.VISIBLE && tempCounterFiles != 0)
                    listFiles.setVisibility(View.VISIBLE);
                if (categoryDirectories.getVisibility() != View.VISIBLE && tempCounterDirectories != 0)
                    categoryDirectories.setVisibility(View.VISIBLE);
                if (categoryFiles.getVisibility() != View.VISIBLE && tempCounterFiles != 0)
                    categoryFiles.setVisibility(View.VISIBLE);
            }
            // Show total size with at least one directory or file and size is not zero.
            if (tempCounterFiles + tempCounterDirectories > 1 && tempSizeTotal > 0) {
                StringBuilder builderTotal = new StringBuilder().append(c.getString(R.string.total)).append(" ").append(Formatter.formatFileSize(c, tempSizeTotal));
                total.setText(builderTotal);
                if (total.getVisibility() != View.VISIBLE)
                    total.setVisibility(View.VISIBLE);
            } else {
                total.setVisibility(View.GONE);
            }
        }
    }.execute();
    // Set category text color for Jelly Bean (API 16) and later.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        categoryDirectories.setTextColor(accentColor);
        categoryFiles.setTextColor(accentColor);
    }
    // Show dialog on screen.
    dialog.show();
}
Also used : LinearLayout(android.widget.LinearLayout) PreferencesConstants(com.amaze.filemanager.fragments.preference_fragments.PreferencesConstants) ColorUsage(com.amaze.filemanager.utils.color.ColorUsage) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) Uri(android.net.Uri) WindowManager(android.view.WindowManager) TextInputLayout(android.support.design.widget.TextInputLayout) ThemedActivity(com.amaze.filemanager.activities.superclasses.ThemedActivity) AppTheme(com.amaze.filemanager.utils.theme.AppTheme) CompressedHelper(com.amaze.filemanager.filesystem.compressed.CompressedHelper) RootHelper(com.amaze.filemanager.filesystem.RootHelper) GeneralSecurityException(java.security.GeneralSecurityException) CheckBox(android.widget.CheckBox) View(android.view.View) Button(android.widget.Button) RootUtils(com.amaze.filemanager.utils.RootUtils) PreferenceManager(android.preference.PreferenceManager) PieChart(com.github.mikephil.charting.charts.PieChart) PieData(com.github.mikephil.charting.data.PieData) LoadFolderSpaceDataTask(com.amaze.filemanager.asynchronous.asynctasks.LoadFolderSpaceDataTask) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) M(android.os.Build.VERSION_CODES.M) AsyncTask(android.os.AsyncTask) Entry(com.github.mikephil.charting.data.Entry) InputType(android.text.InputType) FingerprintManager(android.hardware.fingerprint.FingerprintManager) Executors(java.util.concurrent.Executors) CryptUtil(com.amaze.filemanager.utils.files.CryptUtil) List(java.util.List) TextView(android.widget.TextView) HiddenAdapter(com.amaze.filemanager.adapters.HiddenAdapter) R(com.amaze.filemanager.R) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) CountItemsOrAndSizeTask(com.amaze.filemanager.asynchronous.asynctasks.CountItemsOrAndSizeTask) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Legend(com.github.mikephil.charting.components.Legend) Typeface(android.graphics.Typeface) Context(android.content.Context) IValueFormatter(com.github.mikephil.charting.formatter.IValueFormatter) HybridFile(com.amaze.filemanager.filesystem.HybridFile) MainFragment(com.amaze.filemanager.fragments.MainFragment) FingerprintHandler(com.amaze.filemanager.utils.FingerprintHandler) Intent(android.content.Intent) RequiresApi(android.support.annotation.RequiresApi) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) AppsListFragment(com.amaze.filemanager.fragments.AppsListFragment) Editable(android.text.Editable) InputMethodManager(android.view.inputmethod.InputMethodManager) MainActivity(com.amaze.filemanager.activities.MainActivity) ArrayList(java.util.ArrayList) AppCompatButton(android.support.v7.widget.AppCompatButton) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) PieDataSet(com.github.mikephil.charting.data.PieDataSet) Toast(android.widget.Toast) DataUtils(com.amaze.filemanager.utils.DataUtils) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) ExecutorService(java.util.concurrent.ExecutorService) Formatter(android.text.format.Formatter) GenerateHashesTask(com.amaze.filemanager.asynchronous.asynctasks.GenerateHashesTask) SpannableString(android.text.SpannableString) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) File(java.io.File) Theme(com.afollestad.materialdialogs.Theme) EncryptDecryptUtils(com.amaze.filemanager.utils.files.EncryptDecryptUtils) Color(android.graphics.Color) Utils(com.amaze.filemanager.utils.Utils) SharedPreferences(android.content.SharedPreferences) BasicActivity(com.amaze.filemanager.activities.superclasses.BasicActivity) ViewPortHandler(com.github.mikephil.charting.utils.ViewPortHandler) FileUtils(com.amaze.filemanager.utils.files.FileUtils) DialogUtils(com.afollestad.materialdialogs.util.DialogUtils) TextInputEditText(android.support.design.widget.TextInputEditText) PieEntry(com.github.mikephil.charting.data.PieEntry) OpenMode(com.amaze.filemanager.utils.OpenMode) EditText(android.widget.EditText) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) ArrayList(java.util.ArrayList) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) TextView(android.widget.TextView)

Example 52 with AsyncTask

use of android.os.AsyncTask in project SilicaGel by Siketyan.

the class TwitterAuthActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
    setContentView(R.layout.activity_twitterauth);
    Intent intent = getIntent();
    if (intent == null || intent.getData() == null || !intent.getData().toString().startsWith(SettingsActivity.CALLBACK_URL)) {
        return;
    }
    String verifier = intent.getData().getQueryParameter("oauth_verifier");
    AsyncTask<String, Void, AccessToken> task = new AsyncTask<String, Void, AccessToken>() {

        @Override
        protected AccessToken doInBackground(String... params) {
            try {
                return SettingsActivity.getContext().twitter.getOAuthAccessToken(SettingsActivity.getContext().requestToken, params[0]);
            } catch (TwitterException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(AccessToken accessToken) {
            if (accessToken != null) {
                showToast(getString(R.string.twitter_authorized));
                TwitterUtil.storeAccessToken(SettingsActivity.getContext(), accessToken);
            } else {
                showToast(getString(R.string.twitter_failed));
            }
            startActivity(new Intent(TwitterAuthActivity.this, SettingsActivity.class));
            finish();
        }
    };
    task.execute(verifier);
}
Also used : AccessToken(twitter4j.auth.AccessToken) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) TwitterException(twitter4j.TwitterException)

Example 53 with AsyncTask

use of android.os.AsyncTask in project SilicaGel by Siketyan.

the class NotificationService method onNotificationPosted.

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Log.d(LOG_TAG, "[Notification] " + sbn.getPackageName());
    String player = getPlayer(sbn.getPackageName());
    if (player == null)
        return;
    try {
        final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        if (!pref.getBoolean("monitor_notifications", true))
            return;
        final Bundle extras = sbn.getNotification().extras;
        String title = "";
        String artist = "";
        String album = "";
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        try {
            title = extras.getCharSequence(Notification.EXTRA_TITLE).toString();
            artist = extras.getCharSequence(Notification.EXTRA_TEXT).toString();
            album = extras.getCharSequence(Notification.EXTRA_SUB_TEXT).toString();
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "[Error] Empty title, artist or album was provided.");
        }
        if (title == null || title.isEmpty())
            return;
        Log.d(LOG_TAG, "[Playing] " + title + " - " + artist + " (" + album + ") on " + player);
        String tweetText = pref.getString("template", "").replaceAll("%title%", title).replaceAll("%artist%", artist).replaceAll("%album%", album).replaceAll("%player%", player);
        if (tweetText.equals(previous))
            return;
        previous = tweetText;
        tweetText = tweetText.replaceAll("%y%", String.format("%4d", year)).replaceAll("%m%", String.format("%2d", month)).replaceAll("%d%", String.format("%2d", day)).replaceAll("%h%", String.format("%02d", hour)).replaceAll("%i%", String.format("%02d", minute)).replaceAll("%s%", String.format("%02d", second));
        Log.d(LOG_TAG, "[Tweeting] " + tweetText);
        AsyncTask<String, Void, Boolean> task = new AsyncTask<String, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(String... params) {
                try {
                    Twitter twitter = TwitterUtil.getTwitterInstance(getInstance());
                    ByteArrayInputStream bs = null;
                    if (pref.getBoolean("with_cover", false)) {
                        try {
                            Bitmap thumb = (Bitmap) extras.get(Notification.EXTRA_LARGE_ICON);
                            if (thumb == null)
                                thumb = (Bitmap) extras.get(Notification.EXTRA_LARGE_ICON_BIG);
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            thumb.compress(Bitmap.CompressFormat.PNG, 0, bos);
                            byte[] bitmap = bos.toByteArray();
                            bs = new ByteArrayInputStream(bitmap);
                        } catch (Exception e) {
                            notifyException(NotificationService.this, e);
                        }
                    }
                    if (bs != null) {
                        twitter.updateStatus(new StatusUpdate(params[0]).media("cover.png", bs));
                    } else {
                        twitter.updateStatus(params[0]);
                    }
                    Log.d(LOG_TAG, "[Tweeted] " + params[0]);
                    return true;
                } catch (Exception e) {
                    notifyException(NotificationService.this, e);
                    e.printStackTrace();
                    Log.d(LOG_TAG, "[Error] Failed to tweet.");
                    return false;
                }
            }

            @Override
            protected void onPostExecute(Boolean b) {
                if (pref.getBoolean("notify_tweeted", true)) {
                    Toast.makeText(NotificationService.this, R.string.tweeted, Toast.LENGTH_SHORT).show();
                }
            }
        };
        task.execute(tweetText);
    } catch (Exception e) {
        notifyException(this, e);
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Calendar(java.util.Calendar) AsyncTask(android.os.AsyncTask) Twitter(twitter4j.Twitter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StatusUpdate(twitter4j.StatusUpdate) Bitmap(android.graphics.Bitmap) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 54 with AsyncTask

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

the class CallLogAdapter method loadAndRender.

private void loadAndRender(final CallLogListItemViewHolder views, final long rowId, final PhoneCallDetails details, final CallDetailsEntries callDetailsEntries) {
    LogUtil.d("CallLogAdapter.loadAndRender", "position: %d", views.getAdapterPosition());
    // Reset block and spam information since this view could be reused which may contain
    // outdated data.
    views.isSpam = false;
    views.blockId = null;
    views.isSpamFeatureEnabled = false;
    // Attempt to set the isCallComposerCapable field. If capabilities are unknown for this number,
    // the value will be false while capabilities are requested. mExpandCollapseListener will
    // attempt to set the field properly in that case
    views.isCallComposerCapable = isCallComposerCapable(views.number);
    CallDetailsEntries updatedCallDetailsEntries = generateAndMapNewCallDetailsEntriesHistoryResults(views.number, callDetailsEntries, getAllHistoricalData(views.number, callDetailsEntries));
    views.setDetailedPhoneDetails(updatedCallDetailsEntries);
    views.lightbringerReady = getLightbringer().isReachable(mActivity, views.number);
    final AsyncTask<Void, Void, Boolean> loadDataTask = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... params) {
            views.blockId = mFilteredNumberAsyncQueryHandler.getBlockedIdSynchronous(views.number, views.countryIso);
            details.isBlocked = views.blockId != null;
            if (isCancelled()) {
                return false;
            }
            if (mIsSpamEnabled) {
                views.isSpamFeatureEnabled = true;
                // Only display the call as a spam call if there are incoming calls in the list.
                // Call log cards with only outgoing calls should never be displayed as spam.
                views.isSpam = details.hasIncomingCalls() && Spam.get(mActivity).checkSpamStatusSynchronous(views.number, views.countryIso);
                details.isSpam = views.isSpam;
            }
            return !isCancelled() && loadData(views, rowId, details);
        }

        @Override
        protected void onPostExecute(Boolean success) {
            views.isLoaded = true;
            if (success) {
                int currentGroup = getDayGroupForCall(views.rowId);
                if (currentGroup != details.previousGroup) {
                    views.dayGroupHeaderVisibility = View.VISIBLE;
                    views.dayGroupHeaderText = getGroupDescription(currentGroup);
                } else {
                    views.dayGroupHeaderVisibility = View.GONE;
                }
                render(views, details, rowId);
            }
        }
    };
    views.asyncTask = loadDataTask;
    mAsyncTaskExecutor.submit(LOAD_DATA_TASK_IDENTIFIER, loadDataTask);
}
Also used : CallDetailsEntries(com.android.dialer.calldetails.CallDetailsEntries) AsyncTask(android.os.AsyncTask)

Example 55 with AsyncTask

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

the class FilteredNumbersUtil method importSendToVoicemailContacts.

/**
 * Blocks all the phone numbers of any contacts marked as SEND_TO_VOICEMAIL, then clears the
 * SEND_TO_VOICEMAIL flag on those contacts.
 */
public static void importSendToVoicemailContacts(final Context context, final ImportSendToVoicemailContactsListener listener) {
    Logger.get(context).logInteraction(InteractionEvent.Type.IMPORT_SEND_TO_VOICEMAIL);
    final FilteredNumberAsyncQueryHandler mFilteredNumberAsyncQueryHandler = new FilteredNumberAsyncQueryHandler(context);
    final AsyncTask<Object, Void, Boolean> task = new AsyncTask<Object, Void, Boolean>() {

        @Override
        public Boolean doInBackground(Object... params) {
            if (context == null) {
                return false;
            }
            // Get the phone number of contacts marked as SEND_TO_VOICEMAIL.
            final Cursor phoneCursor = context.getContentResolver().query(Phone.CONTENT_URI, PhoneQuery.PROJECTION, PhoneQuery.SELECT_SEND_TO_VOICEMAIL_TRUE, null, null);
            if (phoneCursor == null) {
                return false;
            }
            try {
                while (phoneCursor.moveToNext()) {
                    final String normalizedNumber = phoneCursor.getString(PhoneQuery.NORMALIZED_NUMBER_COLUMN_INDEX);
                    final String number = phoneCursor.getString(PhoneQuery.NUMBER_COLUMN_INDEX);
                    if (normalizedNumber != null) {
                        // Block the phone number of the contact.
                        mFilteredNumberAsyncQueryHandler.blockNumber(null, normalizedNumber, number, null);
                    }
                }
            } finally {
                phoneCursor.close();
            }
            // Clear SEND_TO_VOICEMAIL on all contacts. The setting has been imported to Dialer.
            ContentValues newValues = new ContentValues();
            newValues.put(Contacts.SEND_TO_VOICEMAIL, 0);
            context.getContentResolver().update(Contacts.CONTENT_URI, newValues, ContactsQuery.SELECT_SEND_TO_VOICEMAIL_TRUE, null);
            return true;
        }

        @Override
        public void onPostExecute(Boolean success) {
            if (success) {
                if (listener != null) {
                    listener.onImportComplete();
                }
            } else if (context != null) {
                String toastStr = context.getString(R.string.send_to_voicemail_import_failed);
                Toast.makeText(context, toastStr, Toast.LENGTH_SHORT).show();
            }
        }
    };
    task.execute();
}
Also used : ContentValues(android.content.ContentValues) AsyncTask(android.os.AsyncTask) Cursor(android.database.Cursor)

Aggregations

AsyncTask (android.os.AsyncTask)394 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