List of usage examples for android.os AsyncTask execute
@MainThread public static void execute(Runnable runnable)
From source file:com.android.gallery3d.gadget.WidgetConfigure.java
private void setPhotoWidget() { AsyncTask.execute(new Runnable() { @Override//from w w w . ja va 2 s .c o m public void run() { Bitmap bitmap = null; InputStream stream = null; try { stream = WidgetConfigure.this.getContentResolver().openInputStream(mCropDst); if (stream != null) { bitmap = BitmapFactory.decodeStream(stream); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } getContentResolver().delete(mCropSrc, null, null); getContentResolver().delete(mCropDst, null, null); } if (bitmap == null) { setResult(Activity.RESULT_CANCELED); finish(); return; } WidgetDatabaseHelper helper = new WidgetDatabaseHelper(WidgetConfigure.this); try { helper.setPhoto(mAppWidgetId, mPickedItem, bitmap); updateWidgetAndFinish(helper.getEntry(mAppWidgetId)); } finally { helper.close(); } } }); }
From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java
private void sendPost(final File file, final ApiCallType apiCallType, final String label) { AsyncTask<File, Void, String> task = new AsyncTask<File, Void, String>() { private boolean success_call = false; @Override//from w ww. j a v a 2s. c o m protected void onCancelled() { super.onCancelled(); if (apiCallType != ApiCallType.GUESS_IMAGE) { resetPredictionsView(predictions, true); } if (success_call && apiCallType == ApiCallType.GUESS_IMAGE) { saveButton.setVisibility(View.VISIBLE); } loader.setVisibility(View.INVISIBLE); file.delete(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (apiCallType != ApiCallType.GUESS_IMAGE) { resetPredictionsView(predictions, true); } if (success_call && apiCallType == ApiCallType.GUESS_IMAGE) { saveButton.setVisibility(View.VISIBLE); } loader.setVisibility(View.INVISIBLE); file.delete(); } @Override protected String doInBackground(File... files) { String responseString = ""; try { String endpointURL = Constants.guessAPI; String callType = ""; switch (apiCallType) { case NEGATIVE_FEEDBACK: callType = "neg"; break; case POSITIVE_FEEDBACK: callType = "pos"; break; case GUESS_IMAGE: default: callType = "guess"; } Log.e("sendPost", "Trying API " + endpointURL); MultipartUtility multipart = new MultipartUtility(endpointURL, "utf8"); // label is only needed if we're sending pos/neg feedback if (!callType.equals("guess")) { multipart.addFormField("label", label); } multipart.addFormField("call_type", callType); multipart.addFilePart("file", file); String TAG = "upload"; List<String> response = multipart.finish(); Log.e(TAG, "SERVER REPLIED:"); for (String line : response) { Log.e(TAG, "Upload Files Response:::" + line); // get your server response here. responseString += line; } success_call = true; } catch (final IOException e) { e.printStackTrace(); Log.e("sendPost", e.getMessage()); EasyPaint.this.runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }); success_call = false; } try { JSONObject jObject = new JSONObject(responseString); if (apiCallType == ApiCallType.GUESS_IMAGE) { refreshLabels(jObject); } else { EasyPaint.this.runOnUiThread(new Runnable() { public void run() { saveButton.setVisibility(View.INVISIBLE); Toast.makeText(getApplicationContext(), R.string.feedback_submitted, Toast.LENGTH_LONG).show(); } }); } } catch (final JSONException e) { e.printStackTrace(); Log.e("sendPost", e.getMessage()); EasyPaint.this.runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }); success_call = false; } return responseString; } }; task.execute(file); }
From source file:com.numenta.taurus.instance.InstanceListActivity.java
/** * Clear any notifications//from w ww .jav a 2 s . c o m */ private void clearNotifications() { AsyncTask.execute(new Runnable() { @Override public void run() { NotificationUtils.resetGroupedNotifications(); ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll(); } }); }
From source file:es.usc.citius.servando.calendula.activities.ConfirmSchedulesActivity.java
private void saveSchedules() { final ProgressDialog progress = ProgressDialog.show(this, "Calendula", "Actualizando pautas...", true); AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() { @Override/*from w w w .j a v a 2s .co m*/ protected Boolean doInBackground(Void... arg0) { try { TransactionManager.callInTransaction(DB.helper().getConnectionSource(), new Callable<Object>() { @Override public Object call() throws Exception { for (int i = 0; i < scheduleCount; i++) { Log.d("PRESCRIPTION", "Item " + i); Fragment f = getViewPagerFragment(i + 1); if (f instanceof ScheduleImportFragment) { Log.d("PRESCRIPTION", "Fragment " + i); ScheduleImportFragment c = (ScheduleImportFragment) f; if (c.validate()) { PrescriptionWrapper w = prescriptionList.get(i); Log.d("PRESCRIPTION", "Validate!"); String cn = w.cn; Medicine m = null; if (cn != null) { m = DB.medicines().findByCnAndPatient(cn, patient); if (m == null) { Log.d("PRESCRIPTION", "Saving medicine!"); m = Medicine.fromPrescription(Prescription.findByCn(cn)); m.setPatient(patient); m.save(); } } else if (w.isGroup) { m = DB.medicines().findByGroupAndPatient(w.group.getId(), patient); if (m == null) { m = new Medicine(Strings.firstPart(w.group.name)); m.setHomogeneousGroup(w.group.getId()); Presentation pres = Presentation.expected(w.group.name, w.group.name); m.setPresentation(pres != null ? pres : Presentation.PILLS); m.setPatient(patient); m.save(); } } else { throw new RuntimeException( " Prescription must have a cn or group reference"); } Schedule s = c.getSchedule(); Schedule prev = DB.schedules().findByMedicineAndPatient(m, patient); // TODO: find by med and patient if (prev != null) { Log.d("PRESCRIPTION", "Found previous schedule for med " + m.getId()); updateSchedule(prev, s, c.getScheduleItems()); } else { Log.d("PRESCRIPTION", "Not found previous schedule for med " + m.getId()); createSchedule(s, c.getScheduleItems(), m); } if (m != null) { // remove old pickups before inserting the new ones DB.pickups().removeByMed(m); } if (m != null && w.pk != null && w.pk.size() > 0) { for (PickupWrapper pkw : w.pk) { PickupInfo pickupInfo = new PickupInfo(); pickupInfo.setTo(df.parseLocalDate(pkw.t).plusMonths(19)); pickupInfo.setFrom(df.parseLocalDate(pkw.f).plusMonths(19)); pickupInfo.taken(pkw.tk == 1 ? true : false); pickupInfo.setMedicine(m); DB.pickups().save(pickupInfo); } } } else { mViewPager.setCurrentItem(i + 1); Snack.show("Hmmmmmm....", ConfirmSchedulesActivity.this); } } } CalendulaApp.eventBus().post(PersistenceEvents.SCHEDULE_EVENT); AlarmScheduler.instance().updateAllAlarms(ConfirmSchedulesActivity.this); return null; } }); return true; } catch (Exception e) { Log.e("ConfirmSchedulesAct", "Error saving prescriptions", e); return false; } } @Override protected void onPostExecute(Boolean result) { if (progress != null) { progress.dismiss(); } if (result) { finish(); } } }; task.execute((Void[]) null); }
From source file:com.android.gallery3d.gadget.WidgetConfigure.java
private void setChoosenPhoto(final Intent data) { AsyncTask.execute(new Runnable() { @Override//from w w w . jav a 2s . c o m public void run() { Resources res = getResources(); float width = res.getDimension(R.dimen.appwidget_width); float height = res.getDimension(R.dimen.appwidget_height); // We try to crop a larger image (by scale factor), but there is still // a bound on the binder limit. float scale = Math.min(WIDGET_SCALE_FACTOR, MAX_WIDGET_SIDE / Math.max(width, height)); int widgetWidth = Math.round(width * scale); int widgetHeight = Math.round(height * scale); File cropSrc = new File(getCacheDir(), "crop_source.png"); File cropDst = new File(getCacheDir(), "crop_dest.png"); mPickedItem = data.getData(); if (!copyUriToFile(mPickedItem, cropSrc)) { setResult(Activity.RESULT_CANCELED); finish(); return; } mCropSrc = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider", new File(cropSrc.getAbsolutePath())); mCropDst = FileProvider.getUriForFile(WidgetConfigure.this, "com.android.gallery3d.fileprovider", new File(cropDst.getAbsolutePath())); Intent request = new Intent(CropActivity.CROP_ACTION).putExtra(CropExtras.KEY_OUTPUT_X, widgetWidth) .putExtra(CropExtras.KEY_OUTPUT_Y, widgetHeight) .putExtra(CropExtras.KEY_ASPECT_X, widgetWidth) .putExtra(CropExtras.KEY_ASPECT_Y, widgetHeight) .putExtra(CropExtras.KEY_SCALE_UP_IF_NEEDED, true).putExtra(CropExtras.KEY_SCALE, true) .putExtra(CropExtras.KEY_RETURN_DATA, false).setDataAndType(mCropSrc, "image/*") .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); request.putExtra(MediaStore.EXTRA_OUTPUT, mCropDst); request.setClipData(ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, mCropDst)); startActivityForResult(request, REQUEST_CROP_IMAGE); } }); }
From source file:cz.maresmar.sfm.view.credential.LoginListActivity.java
private void deleteCredentials(Uri portalUri, Uri credentialUri) { AsyncTask.execute(() -> { int deletedRows = getContentResolver().delete(credentialUri, null, null); if (BuildConfig.DEBUG) { Assert.isOne(deletedRows);/*from ww w . ja va2 s . c o m*/ } }); }
From source file:com.example.google.play.apkx.SampleDownloaderActivity.java
/** * Go through each of the Expansion APK files and open each as a zip file. * Calculate the CRC for each file and return false if any fail to match. * * @return true if XAPKZipFile is successful *//* ww w .j av a2 s .c om*/ void validateXAPKZipFiles() { AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() { @Override protected void onPreExecute() { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_verifying_download); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mCancelValidation = true; } }); mPauseButton.setText(R.string.text_button_cancel_verify); super.onPreExecute(); } @Override protected Boolean doInBackground(Object... params) { for (XAPKFile xf : xAPKS) { String fileName = Helpers.getExpansionAPKFileName(SampleDownloaderActivity.this, xf.mIsMain, xf.mFileVersion); if (!Helpers.doesFileExist(SampleDownloaderActivity.this, fileName, xf.mFileSize, false)) return false; fileName = Helpers.generateSaveFileName(SampleDownloaderActivity.this, fileName); ZipResourceFile zrf; byte[] buf = new byte[1024 * 256]; try { zrf = new ZipResourceFile(fileName); ZipEntryRO[] entries = zrf.getAllEntries(); /** * First calculate the total compressed length */ long totalCompressedLength = 0; for (ZipEntryRO entry : entries) { totalCompressedLength += entry.mCompressedLength; } float averageVerifySpeed = 0; long totalBytesRemaining = totalCompressedLength; long timeRemaining; /** * Then calculate a CRC for every file in the * Zip file, comparing it to what is stored in * the Zip directory. Note that for compressed * Zip files we must extract the contents to do * this comparison. */ for (ZipEntryRO entry : entries) { if (-1 != entry.mCRC32) { long length = entry.mUncompressedLength; CRC32 crc = new CRC32(); DataInputStream dis = null; try { dis = new DataInputStream(zrf.getInputStream(entry.mFileName)); long startTime = SystemClock.uptimeMillis(); while (length > 0) { int seek = (int) (length > buf.length ? buf.length : length); dis.readFully(buf, 0, seek); crc.update(buf, 0, seek); length -= seek; long currentTime = SystemClock.uptimeMillis(); long timePassed = currentTime - startTime; if (timePassed > 0) { float currentSpeedSample = (float) seek / (float) timePassed; if (0 != averageVerifySpeed) { averageVerifySpeed = SMOOTHING_FACTOR * currentSpeedSample + (1 - SMOOTHING_FACTOR) * averageVerifySpeed; } else { averageVerifySpeed = currentSpeedSample; } totalBytesRemaining -= seek; timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed); this.publishProgress(new DownloadProgressInfo(totalCompressedLength, totalCompressedLength - totalBytesRemaining, timeRemaining, averageVerifySpeed)); } startTime = currentTime; if (mCancelValidation) return true; } if (crc.getValue() != entry.mCRC32) { Log.e(Constants.TAG, "CRC does not match for entry: " + entry.mFileName); Log.e(Constants.TAG, "In file: " + entry.getZipFileName()); return false; } } finally { if (null != dis) { dis.close(); } } } } } catch (IOException e) { e.printStackTrace(); return false; } } return true; } @Override protected void onProgressUpdate(DownloadProgressInfo... values) { onDownloadProgress(values[0]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Boolean result) { if (result) { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_validation_complete); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startMovie(); } }); mPauseButton.setText(android.R.string.ok); } else { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_validation_failed); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); mPauseButton.setText(android.R.string.cancel); } super.onPostExecute(result); } }; validationTask.execute(new Object()); }
From source file:cz.maresmar.sfm.view.order.OrderFragment.java
private void deleteOrder(long orderId) { AsyncTask.execute(() -> { Uri orderUri = ContentUris.withAppendedId(Uri.withAppendedPath(mUserUri, ProviderContract.ACTION_PATH), orderId);//from ww w . j av a2 s.c o m int deletedRows = getContext().getContentResolver().delete(orderUri, null, null); if (BuildConfig.DEBUG) { Assert.isOne(deletedRows); } }); }
From source file:com.brandroidtools.filemanager.fragments.NavigationFragment.java
/** * Method that changes the current directory of the view. * * @param newDir The new directory location * @param addToHistory Add the directory to history * @param reload Force the reload of the data * @param useCurrent If this method must use the actual data (for back actions) * @param searchInfo The search information (if calling activity is {@link "SearchActivity"}) * @param scrollTo If not null, then listview must scroll to this item */// w w w. ja v a2 s . c o m private void changeCurrentDir(final String newDir, final boolean addToHistory, final boolean reload, final boolean useCurrent, final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) { // Check navigation security (don't allow to go outside the ChRooted environment if one // is created) final String fNewDir = checkChRootedNavigation(newDir); synchronized (this.mSync) { //Check that it is really necessary change the directory if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) { return; } final boolean hasChanged = !(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0); final boolean isNewHistory = (this.mCurrentDir != null); //Execute the listing in a background process AsyncTask<String, Integer, List<FileSystemObject>> task = new AsyncTask<String, Integer, List<FileSystemObject>>() { /** * {@inheritDoc} */ @Override protected List<FileSystemObject> doInBackground(String... params) { try { //Reset the custom title view and returns to breadcrumb if (NavigationFragment.this.mTitle != null) { NavigationFragment.this.mTitle.post(new Runnable() { @Override public void run() { try { NavigationFragment.this.mTitle.restoreView(); } catch (Exception e) { e.printStackTrace(); } } }); } //Start of loading data if (NavigationFragment.this.mBreadcrumb != null) { try { NavigationFragment.this.mBreadcrumb.startLoading(); } catch (Throwable ex) { /**NON BLOCK**/ } } //Get the files, resolve links and apply configuration //(sort, hidden, ...) List<FileSystemObject> files = NavigationFragment.this.mFiles; if (!useCurrent) { files = CommandHelper.listFiles(mActivity, fNewDir, null); } return files; } catch (final ConsoleAllocException e) { //Show exception and exists mNavigationViewHolder.post(new Runnable() { @Override public void run() { Log.e(TAG, mActivity.getString(R.string.msgs_cant_create_console), e); DialogHelper.showToast(mActivity, R.string.msgs_cant_create_console, Toast.LENGTH_LONG); mActivity.finish(); } }); return null; } catch (Exception ex) { //End of loading data if (NavigationFragment.this.mBreadcrumb != null) { try { NavigationFragment.this.mBreadcrumb.endLoading(); } catch (Throwable ex2) { /**NON BLOCK**/ } } //Capture exception (attach task, and use listener to do the anim) ExceptionUtil.attachAsyncTask(ex, new AsyncTask<Object, Integer, Boolean>() { private List<FileSystemObject> mTaskFiles = null; @Override @SuppressWarnings({ "unchecked", "unqualified-field-access" }) protected Boolean doInBackground(Object... taskParams) { mTaskFiles = (List<FileSystemObject>) taskParams[0]; return Boolean.TRUE; } @Override @SuppressWarnings("unqualified-field-access") protected void onPostExecute(Boolean result) { if (!result.booleanValue()) { return; } onPostExecuteTask(mTaskFiles, addToHistory, isNewHistory, hasChanged, searchInfo, fNewDir, scrollTo); } }); final ExceptionUtil.OnRelaunchCommandResult exListener = new ExceptionUtil.OnRelaunchCommandResult() { @Override public void onSuccess() { // Do animation fadeEfect(false); } @Override public void onFailed(Throwable cause) { // Do animation fadeEfect(false); } @Override public void onCancelled() { // Do animation fadeEfect(false); } }; ExceptionUtil.translateException(mActivity, ex, false, true, exListener); } return null; } /** * {@inheritDoc} */ @Override protected void onPreExecute() { // Do animation fadeEfect(true); } /** * {@inheritDoc} */ @Override protected void onPostExecute(List<FileSystemObject> files) { if (files != null) { onPostExecuteTask(files, addToHistory, isNewHistory, hasChanged, searchInfo, fNewDir, scrollTo); // Do animation fadeEfect(false); } } /** * Method that performs a fade animation. * * @param out Fade out (true); Fade in (false) */ void fadeEfect(final boolean out) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { Animation fadeAnim = out ? new AlphaAnimation(1, 0) : new AlphaAnimation(0, 1); fadeAnim.setDuration(50L); fadeAnim.setFillAfter(true); fadeAnim.setInterpolator(new AccelerateInterpolator()); mNavigationViewHolder.startAnimation(fadeAnim); } }); } }; task.execute(fNewDir); } }
From source file:com.piusvelte.sonet.core.SelectFriends.java
protected void loadFriends() { mFriends.clear();//from w ww. ja va 2s .co m // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); setListAdapter(sa); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() { @Override protected Boolean doInBackground(Long... params) { boolean loadList = false; SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext()); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(params[0]) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mService = account.getInt(2); } account.close(); String response; switch (mService) { case TWITTER: break; case FACEBOOK: if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) { try { JSONArray friends = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, l = friends.length(); i < l; i++) { JSONObject f = friends.getJSONObject(i); HashMap<String, String> newFriend = new HashMap<String, String>(); newFriend.put(Entities.ESID, f.getString(Sid)); newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid))); newFriend.put(Entities.FRIEND, f.getString(Sname)); // need to alphabetize if (mFriends.isEmpty()) mFriends.add(newFriend); else { String fullName = f.getString(Sname); int spaceIdx = fullName.lastIndexOf(" "); String newFirstName = null; String newLastName = null; if (spaceIdx == -1) newFirstName = fullName; else { newFirstName = fullName.substring(0, spaceIdx++); newLastName = fullName.substring(spaceIdx); } List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>(); for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) { HashMap<String, String> oldFriend = mFriends.get(i2); if (newFriend == null) { newFriends.add(oldFriend); } else { fullName = oldFriend.get(Entities.FRIEND); spaceIdx = fullName.lastIndexOf(" "); String oldFirstName = null; String oldLastName = null; if (spaceIdx == -1) oldFirstName = fullName; else { oldFirstName = fullName.substring(0, spaceIdx++); oldLastName = fullName.substring(spaceIdx); } if (newFirstName == null) { newFriends.add(newFriend); newFriend = null; } else { int comparison = oldFirstName.compareToIgnoreCase(newFirstName); if (comparison == 0) { // compare firstnames if (newLastName == null) { newFriends.add(newFriend); newFriend = null; } else if (oldLastName != null) { comparison = oldLastName.compareToIgnoreCase(newLastName); if (comparison == 0) { newFriends.add(newFriend); newFriend = null; } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } newFriends.add(oldFriend); } } if (newFriend != null) newFriends.add(newFriend); mFriends = newFriends; } } loadList = true; } catch (JSONException e) { Log.e(TAG, e.toString()); } } break; case MYSPACE: break; case LINKEDIN: break; case FOURSQUARE: break; case IDENTICA: break; case GOOGLEPLUS: break; case CHATTER: break; } return loadList; } @Override protected void onPostExecute(Boolean loadList) { if (loadList) { // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); sa.setViewBinder(mViewBinder); setListAdapter(sa); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(mAccountId); }