下面列出了怎么用android.os.AsyncTask的API类实例代码及写法,或者点击链接到github查看源代码。
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
/**
* Execute in background the HTTP calls to add and remove members.
*/
public void asyncUpdateGroup(final String senderId, final String apiKey,
final String groupName, final String groupKey,
Bundle newMembers, Bundle removedMembers) {
final Bundle members2Add = new Bundle(newMembers);
final Bundle members2Remove = new Bundle(removedMembers);
new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... voids) {
if (members2Add.size() > 0) {
addMembers(senderId, apiKey, groupName, groupKey, members2Add);
}
if (members2Remove.size() > 0) {
removeMembers(senderId, apiKey, groupName, groupKey, members2Remove);
}
return null;
}
}.execute();
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "com.suyashsrijan.forcedoze.REMOVE_WHITELIST broadcast intent received");
final String packageName = intent.getStringExtra("packageName");
Log.i(TAG, "Package name received: " + packageName);
if (packageName != null) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
List<String> output = Shell.SH.run("dumpsys deviceidle whitelist -" + packageName);
if (output != null) {
for (String s : output) {
Log.i(TAG, s);
}
} else {
Log.i(TAG, "Error occurred while executing command (" + "dumpsys deviceidle whitelist -packagename" + ")");
}
}
});
} else {
Log.i(TAG, "Package name null or empty");
}
}
private void goToSecondSceneWithDelay() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Log.d(TAG, "Do In Background");
Thread.sleep(3000);
} catch(InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Log.d(TAG, "OnPostExecute");
super.onPostExecute(aVoid);
Flow.get(SceneMainView.this).set(SceneMainSecondKey.create());
}
}.execute();
}
/**
* Retrieves contacts matching an email address.
* Uses raw URI when <code>rawUri</code> is <code>true</code>, makes assets copy otherwise.
*
* @param emailAddress email address to match
* @param callback user provided callback to run at completion
*/
@ReactMethod
public void getContactsByEmailAddress(final String emailAddress, final Callback callback) {
AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(final Void ... params) {
Context context = getReactApplicationContext();
ContentResolver cr = context.getContentResolver();
ContactsProvider contactsProvider = new ContactsProvider(cr);
WritableArray contacts = contactsProvider.getContactsByEmailAddress(emailAddress);
callback.invoke(null, contacts);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
@SuppressLint("StaticFieldLeak")
private void loadTexturesAsync(final Context context) {
if (context == null) {
return;
}
new AsyncTask<Void, Void, Cursor>() {
@Override
protected Cursor doInBackground(Void... nothings) {
return loadTextures();
}
@Override
protected void onPostExecute(Cursor cursor) {
if (!isAdded() || cursor == null) {
return;
}
updateAdapter(context, cursor);
}
}.execute();
}
/**
* Generates the authentication encryption key in a background thread (if necessary).
*/
private static void triggerMacKeyGeneration() {
synchronized (sLock) {
if (sKey != null || sMacKeyGenerator != null) {
return;
}
sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() {
// SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom"
// warns about, so this lint warning can safely be suppressed.
@SuppressLint("TrulyRandom")
@Override
public SecretKey call() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME);
SecureRandom random = new SecureRandom();
SecureRandomInitializer.initialize(random);
generator.init(MAC_KEY_BYTE_COUNT * 8, random);
return generator.generateKey();
}
});
AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator);
}
}
@Override
public void handleButtonPress(int index) {
if (index == 0) {
WifiParsedResult wifiResult = (WifiParsedResult) getResult();
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) {
Log.w(TAG, "No WifiManager available from device");
return;
}
final Activity activity = getActivity();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity.getApplicationContext(), R.string.wifi_changing_network, Toast.LENGTH_SHORT).show();
}
});
new WifiConfigManager(wifiManager).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, wifiResult);
parent.restartPreviewAfterDelay(0L);
}
}
/**
* This method unregister from the GCM services and also pusher
* server in the background mode.
*
* @param context
*/
public static void unregisterInBackground(final Context context) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
gcm.unregister();
// Unregister the GCM info from pusher server.
String regId = Preferences.getPreference(context, Preferences.CURRENT_GCM_ID);
GCMIntentService.removeFromPusher(context, regId);
} catch (IOException e) {
Logger.error(TAG, "GCM Un-registration failed.", e);
}
return null;
}
}.execute();
}
public static void saveChanges(final ExifInterface exifInterface,
final List<ExifItem> editedItems, final Callback callback) {
if (exifInterface == null) {
return;
}
AsyncTask.execute(new Runnable() {
@Override
public void run() {
boolean success = true;
for (ExifItem item : editedItems) {
exifInterface.setAttribute(item.getTag(), item.getValue());
}
try {
exifInterface.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
success = false;
}
if (callback != null) {
callback.done(success);
}
}
});
}
/**
* Retrieves <code>thumbnailPath</code> for contact, or <code>null</code> if not available.
*
* @param contactId contact identifier, <code>recordID</code>
* @param callback callback
*/
@ReactMethod
public void getPhotoForId(final String contactId, final Callback callback) {
AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(final Void ... params) {
Context context = getReactApplicationContext();
ContentResolver cr = context.getContentResolver();
ContactsProvider contactsProvider = new ContactsProvider(cr);
String photoUri = contactsProvider.getPhotoUriFromContactId(contactId);
callback.invoke(null, photoUri);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
public <T> CancelableBackgroundOperation executeApiAsync(Intent data, OpenPgpDataSource dataSource,
OpenPgpDataSink<T> dataSink, final IOpenPgpSinkResultCallback<T> callback) {
Messenger messenger = new Messenger(new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
callback.onProgress(message.arg1, message.arg2);
return true;
}
}));
data.putExtra(EXTRA_PROGRESS_MESSENGER, messenger);
OpenPgpSourceSinkAsyncTask<T> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, dataSink, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
return task;
}
protected void setGroupViewThumb(FileUtil.MediaFileType type, String thumb, ImageView icon, TextView text, RequestOptions options) {
if (type == FileUtil.MediaFileType.MOVIE ||
type == FileUtil.MediaFileType.IMG) {
if (options == null) {
Glide.with(mContext).load(thumb).listener(mRequestListener).into(icon);
} else {
Glide.with(mContext).load(thumb).listener(mRequestListener).apply(options).into(icon);
}
} else if (type == FileUtil.MediaFileType.APP) {
Bitmap b = sLruCache.get(thumb);
if (b == null) {
AppThumbTask task = new AppThumbTask(sLruCache, mContext, icon);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new File(thumb));
} else
icon.setImageBitmap(b);
} else if (type == FileUtil.MediaFileType.MP3) {
text.setText(R.string.music);
} else if (type == FileUtil.MediaFileType.DOC) {
text.setText(R.string.doc);
} else if (type == FileUtil.MediaFileType.RAR) {
text.setText(R.string.rar);
}
}
private void load(Uri uri, OnLoadCompleteListener onLoadCompleteListener, int[] userPages) {
if (!recycled) {
throw new IllegalStateException("Don't call load on a PDF View without recycling it first.");
}
// Manage UserPages if not null
if (userPages != null) {
this.originalUserPages = userPages;
this.filteredUserPages = ArrayUtils.deleteDuplicatedPages(originalUserPages);
this.filteredUserPageIndexes = ArrayUtils.calculateIndexesInDuplicateArray(originalUserPages);
}
this.onLoadCompleteListener = onLoadCompleteListener;
// Start decoding document
decodingAsyncTask = new DecodingAsyncTask(uri, this);
decodingAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
renderingAsyncTask = new RenderingAsyncTask(this);
renderingAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void checkNuxSettings() {
if (nuxMode == ToolTipMode.DISPLAY_ALWAYS) {
String nuxString = getResources().getString(R.string.com_facebook_tooltip_default);
displayNux(nuxString);
} else {
// kick off an async request
final String appId = Utility.getMetadataApplicationId(getContext());
AsyncTask<Void, Void, FetchedAppSettings> task = new AsyncTask<Void, Void, Utility.FetchedAppSettings>() {
@Override
protected FetchedAppSettings doInBackground(Void... params) {
FetchedAppSettings settings = Utility.queryAppSettings(appId, false);
return settings;
}
@Override
protected void onPostExecute(FetchedAppSettings result) {
showNuxPerSettings(result);
}
};
task.execute((Void[])null);
}
}
public void getStargazers(final Repository repository, final GetStargazersCallback callback) {
new AsyncTask<Void, Void, List<Star>>() {
@Override
protected List<Star> doInBackground(Void... params) {
return getStargazersSync(repository);
}
@Override
protected void onPostExecute(List<Star> starList) {
if (starList != null) {
callback.onStargazersLoaded(starList);
} else {
callback.onDataNotAvailable();
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
/**
* Action after download finished of not
*
* @param result flag download success or not
*/
@Override
protected void onPostExecute(Boolean result) {
//notify download complete
if (context != null)
Toast.makeText(context, result == true ?
context.getString(R.string.download_complete) :
context.getString(R.string.download_failed)
, Toast.LENGTH_LONG).show();
//pass the download statue to notification
if (notificationDownloaderFlag) {
notificationManager.cancel(0);
if (result) {
showCompleteNotification();
AppPreference.DownloadStatues(AppConstants.Preferences.DOWNLOAD_SUCCESS);
} else {
showFailedNotification();
AppPreference.DownloadStatues(AppConstants.Preferences.DOWNLOAD_FAILED);
}
}
//run extraction service if zip file or stop service
if (fileExtension.toLowerCase().equals("zip") && result) {
new UnZipping(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, filePath, fileName);
} else {
//send broadcast of success or failed
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(AppConstants.Download.INTENT)
.putExtra(AppConstants.Download.DOWNLOAD, result == true ?
AppConstants.Download.SUCCESS :
AppConstants.Download.FAILED));
if (context instanceof Service)
((Service) context).stopService(new Intent(context, DownloadService.class));
}
}
protected void markNotificationAsReadOnShow(int position, Notification notification) {
try {
new MarkNotificationAsReadTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notification.getId());
ActivityTracker.sendEvent(MainActivity.this, ActivityTracker.CAT_UI, "notification_mark_read_on_show", "", 0L);
notificationsListAdapter.removeNotificationByPosition(position);
notifyDataSetChanged();
} catch (RejectedExecutionException e) {
//nothing to do
}
}
private void asyncLoad(String tag, ImageView imageView, AsyncTask<String, Integer, Bitmap> task) {
Set<ImageView> pendingImages = pendingImagesMap.get(tag);
if (pendingImages == null) {
pendingImages = Collections.newSetFromMap(new WeakHashMap<ImageView, Boolean>()); // create weak set
pendingImagesMap.put(tag, pendingImages);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
pendingImages.add(imageView);
imageView.setTag(tag);
imageView.setImageDrawable(null);
}
public static void maybeInvokeRetrieval(TextView textView,
ParsedResult result,
HistoryManager historyManager,
Context context) {
if (result instanceof URIParsedResult) {
SupplementalInfoRetriever uriRetriever =
new URIResultInfoRetriever(textView, (URIParsedResult) result, historyManager, context);
uriRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
SupplementalInfoRetriever titleRetriever =
new TitleRetriever(textView, (URIParsedResult) result, historyManager);
titleRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else if (result instanceof ProductParsedResult) {
ProductParsedResult productParsedResult = (ProductParsedResult) result;
String productID = productParsedResult.getProductID();
SupplementalInfoRetriever productRetriever =
new ProductResultInfoRetriever(textView, productID, historyManager, context);
productRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else if (result instanceof ISBNParsedResult) {
String isbn = ((ISBNParsedResult) result).getISBN();
SupplementalInfoRetriever productInfoRetriever =
new ProductResultInfoRetriever(textView, isbn, historyManager, context);
productInfoRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
SupplementalInfoRetriever bookInfoRetriever =
new BookResultInfoRetriever(textView, isbn, historyManager, context);
bookInfoRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void initData()
{
IMedia media = ((EditorActivityListener) a).media();
String[] dateAndTime = TimeUtility.millisecondsToDatestampAndTimestamp(((EditorActivityListener) a).media().dcimEntry.timeCaptured);
historyHeaderSubTitle.setText(getString(R.string.editor_image_taken, dateAndTime[0] + " " + dateAndTime[1]));
AsyncTask<Void, Void, List<INotification>> taskLoadNotifications = new AsyncTask<Void, Void, List<INotification>>()
{
@Override
protected List<INotification> doInBackground(Void... params) {
return InformaCam.getInstance().notificationsManifest.sortBy(Models.INotificationManifest.Sort.DATE_DESC);
}
@Override
protected void onPostExecute(List<INotification> result) {
super.onPostExecute(result);
lvHistory.setAdapter(new MediaHistoryListAdapter(a, ((EditorActivityListener) a).media()._id, result));
if (lvHistory.getAdapter().getCount() == 0)
{
historyHeader.setOnClickListener(null);
// showHistoryIndicator.setVisibility(View.GONE);
}
else
{
historyHeader.setOnClickListener(OverviewFormFragment.this);
// showHistoryIndicator.setVisibility(View.VISIBLE);
}
}
};
taskLoadNotifications.execute((Void)null);
}
@SuppressLint("NewApi")
private void executeDownloadTask(ArrayList<PageModel> novels) {
downloadTask = new DownloadNovelDetailsTask(this);
String key = DisplayTeaserListActivity.TAG + ":" + novels.get(0).getPage();
if (novels == null || novels.size() == 0) {
Log.w(TAG, getResources().getString(R.string.error_empty_download_array));
return;
}
if (novels.size() > 1) {
key = DisplayTeaserListActivity.TAG + ":All_Teasers";
}
boolean isAdded = LNReaderApplication.getInstance().addTask(key, task);
if (isAdded) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, novels.toArray(new PageModel[novels.size()]));
else
downloadTask.execute(novels.toArray(new PageModel[novels.size()]));
} else {
Log.i(TAG, "Continue download task: " + key);
DownloadNovelDetailsTask tempTask = (DownloadNovelDetailsTask) LNReaderApplication.getInstance().getTask(key);
if (tempTask != null) {
downloadTask = tempTask;
downloadTask.owner = this;
}
toggleProgressBar(true);
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
setFastScrollColor(mFastScroll);
mFastScroll.attachRecyclerView(mRecyclerView);
mAsyncTask = new FAQsLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private synchronized void autoFocusAgainLater() {
if (!stopped && outstandingTask == null) {
AutoFocusTask newTask = new AutoFocusTask();
try {
if (Build.VERSION.SDK_INT >= 11) {
newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
newTask.execute();
}
outstandingTask = newTask;
} catch (RejectedExecutionException ree) {
Log.w(TAG, "Could not request auto focus", ree);
}
}
}
private synchronized void cancelOutstandingTask() {
if (outstandingTask != null) {
if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
outstandingTask.cancel(true);
}
outstandingTask = null;
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),
getActivity().getResources().getInteger(R.integer.wallpapers_column_count)));
mRecyclerView.setHasFixedSize(false);
if (WallpaperBoardApplication.getConfig().getWallpapersGrid() ==
WallpaperBoardConfiguration.GridStyle.FLAT) {
int padding = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin);
mRecyclerView.setPadding(padding, padding, 0, 0);
}
resetViewBottomPadding(mRecyclerView, true);
mSwipe.setColorSchemeColors(ColorHelper.getAttributeColor(
getActivity(), R.attr.colorAccent));
mSwipe.setOnRefreshListener(() -> {
if (mAsyncTask != null) {
mSwipe.setRefreshing(false);
return;
}
WallpapersLoaderTask.with(getActivity()).start();
mAsyncTask = new WallpapersTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
});
getWallpapers();
}
private synchronized void cancel() {
AsyncTask<?, ?, ?> task = inactivityTask;
if (task != null) {
task.cancel(true);
inactivityTask = null;
}
}
private void finishEvent(final Event event) {
// Send chosen event to the server
List<String> userRecentEventInfo = new ArrayList<>();
userRecentEventInfo.add(event.getRemoteId());
new RecentEventTask(new AccountDelegate() {
@Override
public void finishAccount(AccountStatus accountStatus) {
// no-op, don't care if server didn't get event selection
}
}, getApplicationContext()).execute(userRecentEventInfo.toArray(new String[userRecentEventInfo.size()]));
try {
UserHelper userHelper = UserHelper.getInstance(getApplicationContext());
User user = userHelper.readCurrentUser();
userHelper.setCurrentEvent(user, event);
} catch (UserException e) {
Log.e(LOG_NAME, "Could not set current event.", e);
}
// disable pushing locations
if (!UserHelper.getInstance(getApplicationContext()).isCurrentUserPartOfEvent(event)) {
SharedPreferences.Editor sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
sp.putBoolean(getString(R.string.reportLocationKey), false).apply();
}
AsyncTask.execute(new Runnable() {
@Override
public void run() {
new ObservationServerFetch(getApplicationContext()).fetch(false);
}
});
setResult(RESULT_OK);
finish();
}
@SuppressLint("StaticFieldLeak")
@Override
public void onReceive(final Context context, Intent intent) {
if (!CLEAR_ACTION.equals(intent.getAction()))
return;
final long[] threadIds = intent.getLongArrayExtra(THREAD_IDS_EXTRA);
if (threadIds != null) {
NotificationManagerCompat.from(context).cancel(intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1));
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
List<MarkedMessageInfo> messageIdsCollection = new LinkedList<>();
for (long threadId : threadIds) {
Log.i(TAG, "Marking as read: " + threadId);
List<MarkedMessageInfo> messageIds = DatabaseFactory.getThreadDatabase(context).setRead(threadId, true);
messageIdsCollection.addAll(messageIds);
}
process(context, messageIdsCollection);
ApplicationDependencies.getMessageNotifier().updateNotification(context);
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
/**
* Handle the newly added key digit. Append the digit to {@link #mPinTyped}.
* If the new digit is {@link KeyNamesBuilder#BACKSPACE_TITLE}, remove the last digit of the {@link #mPinTyped}.
*
* @param newDigit newly pressed digit
*/
private void onKeyPressed(@Nullable String newDigit) {
if (newDigit == null) return;
//Check for the state
if (mAuthenticationListener == null) {
throw new IllegalStateException("Set AuthenticationListener to receive callbacks.");
}
if (newDigit.equals(KeyNamesBuilder.BACKSPACE_TITLE)) { //Back space key is pressed.
if (mPinTyped.size() > 0) mPinTyped.remove(mPinTyped.size() - 1); //Remove last digit.
} else {
//Add new digit
mPinTyped.add(mKeyNamesBuilder.getValueOfKey(newDigit));
}
invalidate();
if (isDynamicPinEnabled() || mPinTyped.size() == mBoxIndicator.getPinLength()) {
if (mPinAuthenticatorTask != null && mPinAuthenticatorTask.getStatus() == AsyncTask.Status.RUNNING)
mPinAuthenticatorTask.cancel(true);
mPinAuthenticatorTask = new PinAuthenticatorTask(mAuthenticator);
//noinspection unchecked
mPinAuthenticatorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mPinTyped);
} else {
giveTactileFeedbackForKeyPress();
}
}