下面列出了怎么用android.os.AsyncTask.Status的API类实例代码及写法,或者点击链接到github查看源代码。
public DownloadTask(final Context context, String username, String password) {
super(context, username, password);
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(1);
progressDialog.setIndeterminate(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(arg0 -> {
if (downloadTask != null && downloadTask.getStatus() != Status.FINISHED) {
downloadTask.cancel(false);
downloadTask = null;
Log.i("down", "cancel");
ManagerNotify.toastShortMessage(context, getString(R.string.cancelled));
}
});
}
private void initCallbacks()
{
_callbacks = getTaskCallbacks(getActivity());
if (_callbacks != null)
{
if(_task.getStatus() != Status.FINISHED)
_callbacks.onPrepare(getArguments());
else
try
{
_callbacks.onCompleted(getArguments(), _task.get());
}
catch (Exception ignored)
{
}
}
}
@UiThread
private void calculatePositionAsync(Activity activity, GeoPoint curPos)
{
if (naviEngineTask == null) { createNaviEngineTask(activity); }
updateDirectTargetDir(curPos);
if (naviEngineTask.getStatus() == Status.RUNNING)
{
log("Error, NaviEngineTask is still running! Drop job ...");
}
else if (naviEngineTask.hasError())
{
naviEngineTask.getError().printStackTrace();
}
else
{
createNaviEngineTask(activity); //TODO: Recreation of Asynctask seems necessary?!
naviEngineTask.execute(curPos);
}
}
public static void getDataSources(OnDataSourceResultListener listener,
boolean force) {
if (mDownloadTask == null
|| mDownloadTask.getStatus() != Status.FINISHED || force) {
mCurrentListeners.add(listener);
if (mDownloadTask == null
|| mDownloadTask.getStatus() == Status.FINISHED) {
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
}
} else {
listener.onDataSourceResult(new ArrayList<PluginDownloadHolder>(
mDownloadableDataSources));
}
}
@Override
public void onBackPressed() {
if (mFlashFirmwareTask != null && mFlashFirmwareTask.getStatus().equals(Status.RUNNING)) {
if (mDoubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.mDoubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to cancel flashing and exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mDoubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
}
}
public void markTaskStatusInProgress(Uri task) {
Log.i(TAG, "markStatusInProgress(): " + task);
org.sana.api.task.Status status = org.sana.api.task.Status.IN_PROGRESS;
String now = timeStamp();
ContentValues values = new ContentValues();
values.put(Tasks.Contract.STATUS, "In Progress");
values.put(Tasks.Contract.MODIFIED, now);
values.put(Tasks.Contract.STARTED, now);
getContentResolver().update(task, values, null, null);
Bundle form = new Bundle();
form.putString(Tasks.Contract.STATUS, "In Progress");
form.putString(Tasks.Contract.MODIFIED, now);
form.putString(Tasks.Contract.STARTED, now);
// send to sync
Intent intent = new Intent(Intents.ACTION_UPDATE, task);
intent.putExtra("form", form);
startService(intent);
}
public void markTaskStatusCompleted(Uri task, Uri encounter) {
Log.i(TAG, "markStatusCompleted(): " + task);
org.sana.api.task.Status status = org.sana.api.task.Status.COMPLETED;
String now = timeStamp();
String uuid = ModelWrapper.getUuid(encounter, getContentResolver());
ContentValues values = new ContentValues();
values.put(Tasks.Contract.STATUS, status.toString());
values.put(Tasks.Contract.COMPLETED, now);
values.put(EncounterTasks.Contract.ENCOUNTER, uuid);
values.put(Tasks.Contract.MODIFIED, now);
Bundle form = new Bundle();
form.putString(Tasks.Contract.STATUS, status.toString());
form.putString(Tasks.Contract.MODIFIED, now);
form.putString(Tasks.Contract.COMPLETED, now);
form.putString(EncounterTasks.Contract.ENCOUNTER, uuid);
// send to sync
Intent intent = new Intent(Intents.ACTION_UPDATE, task);
intent.putExtra("form", form);
startService(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
if (downloadTask != null && downloadTask.getStatus() != Status.FINISHED) {
downloadTask.cancel(true);
downloadTask = null;
}
}
private void fullScreenClickShowAndHide(boolean show) {
LogInfo.log(RxBus.TAG, "全屏控制栏显示:" + show);
if (show) {
this.mTopBar.setVisibility(0);
this.mBottomBar.setVisibility(0);
if (LiveLunboUtils.isLunBoWeiShiType(this.pageIndex)) {
this.mChannelBtn.setVisibility(0);
}
if (this.mLiveBarrageController == null || !this.mLiveBarrageController.getBarrageControl().isOpenBarrage()) {
this.mBarrageInputBtn.setVisibility(4);
} else {
this.mBarrageInputBtn.setVisibility(0);
}
if (this.mCanWatchAndBuy) {
this.mCartLayout.setVisibility(0);
if (this.mCartShowingSubscription != null) {
LogInfo.log(RxBus.TAG, "取消监听购物车按钮消失的通知");
this.mCartShowingSubscription.unsubscribe();
}
}
if (!(LiveLunboUtils.isLunBoWeiShiType(this.pageIndex) || this.mBaseBean == null || this.mBaseBean.branchType <= 0 || this.mBaseBean.isBranch != 1 || BaseTypeUtils.isListEmpty(this.mBaseBean.branches))) {
this.mBtnMultiProgram.setVisibility(0);
}
} else {
this.mTopBar.setVisibility(8);
this.mBottomBar.setVisibility(8);
if (LiveLunboUtils.isLunBoWeiShiType(this.pageIndex)) {
this.mChannelBtn.setVisibility(8);
}
this.mBarrageInputBtn.setVisibility(4);
hideFloatView();
setLevelTipVisible(false);
if (this.mCartLayout.getVisibility() == 0 && !this.mWacthAndBuyFloatView.isShowing() && this.mWatchAndBuyCartListView.getVisibility() != 0 && ((this.mCartTask == null || this.mCartTask.getStatus() != Status.RUNNING) && this.mWatchAndBuyCartListView.getVisibility() != 0)) {
this.mCartLayout.setVisibility(8);
}
this.mBtnMultiProgram.setVisibility(8);
}
RxBus.getInstance().send("rx_bus_live_home_action_update_system_ui");
}
@Override
public void close() {
super.close();
if (mLoadingTask != null && mLoadingTask.getStatus() != Status.FINISHED) {
if(BuildConfig.DEBUG) Log.d(TAG, "Cursor is closed. Cancel the loading task " + mLoadingTask);
// Interrupting the task is not a good choice as it's waiting for the Samba client thread
// returning the result. Interrupting the task only frees the task from waiting for the
// result, rather than freeing the Samba client thread doing the hard work.
mLoadingTask.cancel(false);
}
}
public <T> void runTask(Uri uri, AsyncTask<T, ?, ?> task, T... args) {
synchronized (mTasks) {
if (!mTasks.containsKey(uri) || mTasks.get(uri).getStatus() == Status.FINISHED) {
mTasks.put(uri, task);
// TODO: Use different executor for different servers.
task.executeOnExecutor(mExecutor, args);
} else {
Log.i(TAG,
"Ignore this task for " + uri + " to avoid running multiple updates at the same time.");
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (passwordList == null) {
if (thread.getStatus() == Status.FINISHED
|| thread.getStatus() == Status.RUNNING)
thread = new KeygenThread(wifiNetwork);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
thread.execute();
} else {
thread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
@Override
public boolean onQueryTextSubmit(String query) {
if ((mTask != null) && (mTask.getStatus() == Status.RUNNING)) {
return false;
}
mQuery = query;
mTask = new SearchTask(getActivity());
mTask.execute(query);
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
if ((mTask != null) && (mTask.getStatus() == Status.RUNNING)) {
return false;
}
mQuery = query;
mTask = new SearchTask(getActivity());
mTask.execute(query);
return false;
}
/**
* 加载图片
*/
private void loadImages() {
mLoadingLayout.showLoading(true);
if (!SDcardUtil.hasExternalStorage()) {
mLoadingLayout.showEmpty(getString(R.string.donot_has_sdcard));
return;
}
// 线程正在执行
if (mLoadTask != null && mLoadTask.getStatus() == Status.RUNNING) {
return;
}
mLoadTask = new ImageLoadTask(this, new OnTaskResultListener() {
@SuppressWarnings("unchecked")
@Override
public void onResult(boolean success, String error, Object result) {
mLoadingLayout.showLoading(false);
// 如果加载成功
if (success && result != null && result instanceof ArrayList) {
setImageAdapter((ArrayList<ImageGroup>)result);
} else {
// 加载失败,显示错误提示
mLoadingLayout.showFailed(getString(R.string.loaded_fail));
}
}
});
TaskUtil.execute(mLoadTask);
}
@Override
protected void onPause() {
//TODO: improve
//TODO: why does resetToFirmware not work?
if (mFlashFirmwareTask != null && mFlashFirmwareTask.getStatus().equals(Status.RUNNING)) {
Log.d(LOG_TAG, "OnPause: stop bootloader.");
mFlashFirmwareTask.cancel(true);
}
super.onPause();
}
private void lookupPatient(String patientId) {
logEvent(EventType.ENCOUNTER_LOOKUP_PATIENT_START, patientId);
// Display progress dialog
String message = String.format(getString(R.string.dialog_look_up_patient), patientId);
showProgressDialogFragment(message);
if (patientLookupTask == null || patientLookupTask.getStatus() == Status.FINISHED) {
patientLookupTask = new PatientLookupTask(getActivity());
patientLookupTask.setPatientLookupListener(this);
patientLookupTask.execute(patientId);
}
}
/**
* Executes a task to clear out the database
*/
private void doClearDatabase() {
// TODO: context leak
if (mResetDatabaseTask != null && mResetDatabaseTask.getStatus() != Status.FINISHED)
return;
mResetDatabaseTask =
(ResetDatabaseTask) new ResetDatabaseTask(this, true).execute(this);
}
private void doClearDatabase(Uri[] uris) {
// TODO: context leak
if (mResetDatabaseTask != null && mResetDatabaseTask.getStatus() != Status.FINISHED)
return;
mResetDatabaseTask =
(ResetDatabaseTask) new ResetDatabaseTask(this, true, uris).execute(this);
}
private void saveLocalTaskState(Bundle outState) {
final ResetDatabaseTask rTask = mResetDatabaseTask;
if (rTask != null && rTask.getStatus() != Status.FINISHED) {
rTask.cancel(true);
outState.putBoolean("_resetdb", true);
}
}
/**
* Executes a task to clear out the database
*/
private void doClearDatabase() {
// TODO: context leak
if (mResetDatabaseTask != null && mResetDatabaseTask.getStatus() != Status.FINISHED)
return;
mResetDatabaseTask =
(ResetDatabaseTask) new ResetDatabaseTask(this).execute(this);
}
private void saveLocalTaskState(Bundle outState) {
final MDSSyncTask mTask = mSyncTask;
if (mTask != null && mTask.getStatus() != Status.FINISHED) {
mTask.cancel(true);
outState.putBoolean(STATE_MDS_SYNC, true);
}
final ResetDatabaseTask rTask = mResetDatabaseTask;
if (rTask != null && rTask.getStatus() != Status.FINISHED) {
rTask.cancel(true);
outState.putBoolean(STATE_RESET_DB, true);
}
}
/**
* Executes a task to clear out the database
*/
private void doClearDatabase() {
// TODO: context leak
if (mResetDatabaseTask != null && mResetDatabaseTask.getStatus() != Status.FINISHED)
return;
mResetDatabaseTask =
(ResetDatabaseTask) new ResetDatabaseTask(this).execute(this);
}
private void saveLocalTaskState(Bundle outState) {
final MDSSyncTask mTask = mSyncTask;
if (mTask != null && mTask.getStatus() != Status.FINISHED) {
mTask.cancel(true);
outState.putBoolean(STATE_MDS_SYNC, true);
}
final ResetDatabaseTask rTask = mResetDatabaseTask;
if (rTask != null && rTask.getStatus() != Status.FINISHED) {
rTask.cancel(true);
outState.putBoolean(STATE_RESET_DB, true);
}
}
public boolean addTask(String key, AsyncTask<?, ?, ?> task) {
synchronized (lock) {
if (runningTasks.containsKey(key)) {
AsyncTask<?, ?, ?> tempTask = runningTasks.get(key);
if (tempTask != null && tempTask.getStatus() != Status.FINISHED)
return false;
}
runningTasks.put(key, task);
return true;
}
}
private void displayImage(AbsListView listView) {
int firstPos = listView.getFirstVisiblePosition();
int lastPos = listView.getLastVisiblePosition();
int totalCount = lastPos - firstPos + 1;
Log.v(TAG, "滚动停止加载图片..");
for (int i = 0; i < totalCount; i++) {
View view = listView.getChildAt(i);
Object tag = view.getTag();
if (!(tag instanceof StatusHolder)) {
continue;
}
StatusHolder holder = (StatusHolder)view.getTag();
ImageLoad4ThumbnailTask thumbnailTask = holder.thumbnailTask;
if (thumbnailTask != null
&& thumbnailTask.isCancelled() == false
&& thumbnailTask.getStatus() == Status.PENDING) {
thumbnailTask.execute();
}
QueryResponseCountTask responseCountTask = holder.responseCountTask;
if (responseCountTask != null
&& responseCountTask.isCancelled() == false
&& responseCountTask.getStatus() == Status.PENDING) {
responseCountTask.execute();
}
}
}
private void refreshAction() {
Glide.get(getContext()).clearMemory();
preferences.removeCache(getDateFromArguments());
if (this.loadTask == null
|| this.loadTask.getStatus() != Status.PENDING) {
this.loadTask = new GetStripUrl(getContext(), getStripURIlListener, preferences,
getDateFromArguments(), progress);
}
this.loadTask.execute();
}
private boolean isLoading() {
return (mLoadTask != null && mLoadTask.getStatus() == Status.RUNNING);
}
private boolean isLoading(){
return ((null!=mLoadAppInfoTask)&&(mLoadAppInfoTask.getStatus()==Status.RUNNING));
}
/**
* Reload form record list for current filter status and collect pertinent
* text data using FormRecordLoaderTask; results will then be re-filtered
* and displayed via callbacks.
*/
public void resetRecords() {
// reload the form records, even if they are currently being loaded
if (loader.getStatus() == Status.RUNNING) {
loader.cancel(false);
loader = loader.spawn();
} else if (loader.getStatus() == Status.FINISHED) {
loader = loader.spawn();
}
SqlStorage<FormRecord> storage = CommCareApplication.instance().getUserStorage(FormRecord.class);
// choose a default filter if none set
if (filter == null) {
filter = FormRecordFilter.SubmittedAndPending;
}
records.clear();
String currentAppId = CommCareApplication.instance().getCurrentApp().getAppRecord().getApplicationId();
Vector recordsVector = new Vector();
// Grab all form records that satisfy ANY of the statuses in the filter, AND belong to the
// currently seated app
for (String status : filter.getStatus()) {
recordsVector.addAll(storage.getRecordsForValues(
new String[]{FormRecord.META_STATUS, FormRecord.META_APP_ID},
new Object[]{status, currentAppId}));
}
if (filter.equals(FormRecordFilter.Pending)) {
StorageUtils.sortRecordsBySubmissionOrderingNumber(recordsVector);
} else {
StorageUtils.sortRecordsByLastModifiedTimeDescending(recordsVector);
}
records.addAll(recordsVector);
searchCache.clear();
current.clear();
notifyDataSetChanged();
// load specific data about the 'records' into the searchCache, such as
// record title, form name, modified date
loader.init(searchCache, names);
loader.executeParallel(records.toArray(new FormRecord[records.size()]));
}