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();
}
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);
}
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);
}
}
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);
}
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();
}
Aggregations