Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

In this page you can find the example usage for android.os AsyncTask AsyncTask.

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

protected Task<twitter4j.Status> doTweet(final Twitter instance, final StatusUpdate latestStatus) {
    final Task<twitter4j.Status>.TaskCompletionSource source = Task.create();

    new AsyncTask<StatusUpdate, Void, Object>() {

        @Override/*from ww  w .j a v  a2s . co m*/
        protected Object doInBackground(StatusUpdate... params) {
            try {
                return instance.updateStatus(latestStatus);
            } catch (TwitterException e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o instanceof AccessToken) {
                source.trySetResult((twitter4j.Status) o);
            } else {
                source.trySetError((Exception) o);
            }

        }
    }.execute(latestStatus);
    return source.getTask();
}

From source file:com.microsoft.services.msa.LiveAuthClient.java

/**
 * Attempts to log in a user using multiple non-interactive approaches.
 *
 * A {@link LiveConnectSession} will be returned by calling
 * {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
 * Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
 * called. These methods will be called on the main/UI thread.
 *
 * @param scopes list of scopes which will override scopes from constructor
 * @param userState state object that is pass to listener on completion.
 * @param listener called on either completion or error during the login process.
 * @return false == silent login failed, interactive login required.
 *         true == silent login is continuing on the background thread the listener will be
 *                 called back when it has completed.
 *//*from  w  ww . ja v  a 2s  . c o  m*/
public Boolean loginSilent(final Iterable<String> scopes, final Object userState,
        final LiveAuthListener listener) {

    if (this.hasPendingLoginRequest) {
        throw new IllegalStateException(ErrorMessages.LOGIN_IN_PROGRESS);
    }

    final Iterable<String> activeScopes;
    if (scopes == null) {
        if (this.baseScopes == null) {
            activeScopes = Arrays.asList(new String[0]);
        } else {
            activeScopes = this.baseScopes;
        }
    } else {
        activeScopes = scopes;
    }

    if (TextUtils.isEmpty(this.session.getRefreshToken())) {
        this.session.setRefreshToken(getRefreshTokenFromPreferences());
    }

    // if the session is valid and contains all the scopes, do not display the login ui.
    final boolean needNewAccessToken = this.session.isExpired() || !this.session.contains(activeScopes);
    final boolean attemptingToLoginSilently = TextUtils.isEmpty(this.session.getRefreshToken());

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(final Void... voids) {
            if (!needNewAccessToken) {
                Log.i(TAG, "Access token still valid, so using it.");
                listener.onAuthComplete(LiveStatus.CONNECTED, LiveAuthClient.this.session, userState);
            } else if (tryRefresh(activeScopes)) {
                Log.i(TAG, "Used refresh token to refresh access and refresh tokens.");
                listener.onAuthComplete(LiveStatus.CONNECTED, LiveAuthClient.this.session, userState);
            } else {
                Log.i(TAG, "All tokens expired, you need to call login() to initiate interactive logon");
                listener.onAuthComplete(LiveStatus.NOT_CONNECTED, LiveAuthClient.this.getSession(), userState);
            }
            return null;
        }
    }.execute();

    return !attemptingToLoginSilently;
}

From source file:org.anhonesteffort.flock.SubscriptionStripeFragment.java

private void handleCancelSubscription() {
    if (asyncTask != null)
        return;//from   www . j a va 2s .c  o  m

    asyncTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleCancelSubscription()");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();
            RegistrationApi registrationApi = new RegistrationApi(subscriptionActivity);

            try {

                registrationApi.cancelSubscription(subscriptionActivity.davAccount);

                AccountStore.setLastChargeFailed(subscriptionActivity, false);
                AccountStore.setSubscriptionPlan(subscriptionActivity, SubscriptionPlan.PLAN_NONE);
                AccountStore.setAutoRenew(subscriptionActivity, false);

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (RegistrationApiException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (JsonProcessingException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (IOException e) {
                ErrorToaster.handleBundleError(e, result);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            asyncTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS) {
                new AccountSyncScheduler(subscriptionActivity).requestSync();
                Toast.makeText(subscriptionActivity, R.string.subscription_canceled, Toast.LENGTH_SHORT).show();
                subscriptionActivity.updateFragmentWithPlanType(SubscriptionPlan.PLAN_TYPE_NONE);
            }

            else {
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
                handleUpdateUi();
            }
        }
    }.execute();
}

From source file:com.odoo.addons.crm.models.CRMLead.java

public void createQuotation(final ODataRow lead, final String partnerId, final boolean close,
        final OnOperationSuccessListener listener) {
    new AsyncTask<Void, Void, Void>() {
        private ProgressDialog dialog;

        @Override//from w w  w  . java  2 s .  c o  m
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(mContext);
            dialog.setTitle(R.string.title_please_wait);
            dialog.setMessage(OResource.string(mContext, R.string.title_working));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                odoo.Odoo odoo = getServerDataHelper().getOdoo();
                // Creating wizard record
                JSONObject values = new JSONObject();
                ResPartner resPartner = new ResPartner(mContext, getUser());
                ODataRow partner = resPartner.browse(new String[] {}, Integer.parseInt(partnerId));
                values.put("partner_id", partner.getInt("id"));
                values.put("close", close);
                JSONObject context = new JSONObject();
                context.put("stage_type", lead.getString("type"));
                context.put("active_id", lead.getInt("id"));
                context.put("active_ids", new JSONArray().put(lead.getInt("id")));
                context.put("active_model", "crm.lead");
                odoo.updateContext(context);
                JSONObject result = odoo.createNew("crm.make.sale", values);
                int quotation_wizard_id = result.getInt("result");

                // Creating quotation
                OArguments arg = new OArguments();
                arg.add(quotation_wizard_id);
                arg.add(context);
                odoo.call_kw("crm.make.sale", "makeOrder", arg.get());
                Thread.sleep(500);
                // if close = true
                if (close)
                    _markWonLost("won", lead);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            dialog.dismiss();
            if (listener != null) {
                listener.OnSuccess();
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
            if (listener != null) {
                listener.OnCancelled();
            }
        }
    }.execute();
}

From source file:de.alosdev.android.customerschoice.CustomersChoice.java

private void internalConfigureByNetwork(final Context context, String fileAddress) {
    new AsyncTask<String, Void, Void>() {
        @Override//from   w ww . ja v  a 2 s .com
        protected Void doInBackground(String... args) {
            String value = args[0];
            try {
                final SharedPreferences preferences = getPreferences(context);
                final URL url = new URL(value);
                log.d(TAG, "read from: ", value);

                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);

                // set etag header if existing
                final String fieldEtag = preferences.getString(getPreferencesKey(value, FIELD_ETAG), null);
                if (null != fieldEtag) {
                    conn.setRequestProperty("If-None-Match", fieldEtag);
                }

                // set modified since header if existing
                final long fieldLastModified = preferences
                        .getLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), 0);
                if (fieldLastModified > 0) {
                    conn.setIfModifiedSince(fieldLastModified);
                }
                conn.connect();

                final int response = conn.getResponseCode();

                if (HttpStatus.SC_OK == response) {
                    log.d(TAG, "found file");
                    readFromInputStream(conn.getInputStream());

                    // writing caching information into preferences
                    final Editor editor = preferences.edit();
                    editor.putString(getPreferencesKey(value, FIELD_ETAG), conn.getHeaderField("ETag"));
                    editor.putLong(getPreferencesKey(value, FIELD_LAST_MODIFIED),
                            conn.getHeaderFieldDate("Last-Modified", 0));
                    editor.commit();
                } else if (HttpStatus.SC_NOT_MODIFIED == response) {
                    log.i(TAG, "no updates, file not modified: ", value);
                } else {
                    log.e(TAG, "cannot read from: ", value, " and get following response code:", response);
                }
            } catch (MalformedURLException e) {
                log.e(TAG, e, "the given URL is malformed: ", value);
            } catch (IOException e) {
                log.e(TAG, e, "Error during reading the file: ", value);
            }
            return null;
        }

    }.execute(fileAddress);
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ???.//  w ww. j a va 2  s .  c  om
 * 
 * @param deviceId ?ID
 * @param sessionKey ID
 * @param listener 
 */
public static void asyncUnregisterOnDataAvaible(final String deviceId, final String sessionKey,
        final DConnectMessageHandler listener) {
    AsyncTask<Void, Void, DConnectMessage> task = new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        protected DConnectMessage doInBackground(final Void... params) {
            try {
                DConnectClient client = new HttpDConnectClient();
                HttpDelete request = new HttpDelete(
                        MEDIASTREAM_ON_DATA_AVAILABLE_URI + "?deviceId=" + deviceId + "&sessionKey="
                                + sessionKey + "&" + DConnectMessage.EXTRA_ACCESS_TOKEN + "=" + accessToken);
                HttpResponse response = client.execute(request);
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }
        }

        @Override
        protected void onPostExecute(final DConnectMessage message) {
            if (listener != null) {
                listener.handleMessage(message);
            }
        }
    };
    task.execute();
}

From source file:com.cm.android.beercellar.ui.ImageGridFragment.java

private void callCloudVision(final String imageAbsolutePath, final Bitmap bitmap) throws IOException {
    // Switch text to loading
    // mImageDetails.setText(R.string.loading_message);

    // Do the real work in an async task, because we need to use the network anyway
    new AsyncTask<Object, Void, String>() {
        @Override//from w w  w .  j a  v  a  2 s.  c o  m
        protected String doInBackground(Object... params) {
            try {
                HttpTransport httpTransport = new NetHttpTransport();
                JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

                Vision.Builder builder = new Vision.Builder(httpTransport, jsonFactory, null);
                builder.setVisionRequestInitializer(new VisionRequestInitializer(CLOUD_VISION_API_KEY));
                Vision vision = builder.build();
                builder.setApplicationName(APPLICATION_NAME);

                BatchAnnotateImagesRequest batchAnnotateImagesRequest = new BatchAnnotateImagesRequest();
                batchAnnotateImagesRequest.setRequests(new ArrayList<AnnotateImageRequest>() {
                    {
                        AnnotateImageRequest annotateImageRequest = new AnnotateImageRequest();

                        // Add the image
                        Image base64EncodedImage = new Image();
                        // Convert the bitmap to a JPEG
                        // Just in case it's a format that Android understands but Cloud Vision
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
                        byte[] imageBytes = byteArrayOutputStream.toByteArray();

                        // Base64 encode the JPEG
                        base64EncodedImage.encodeContent(imageBytes);
                        annotateImageRequest.setImage(base64EncodedImage);

                        // add the features we want
                        annotateImageRequest.setFeatures(new ArrayList<Feature>() {
                            {
                                Feature detection = new Feature();
                                detection.setType("TEXT_DETECTION");
                                detection.setMaxResults(1);
                                add(detection);
                            }
                        });

                        // Add the list of one thing to the request
                        add(annotateImageRequest);
                    }
                });

                Vision.Images.Annotate annotateRequest = vision.images().annotate(batchAnnotateImagesRequest);
                // Due to a bug: requests to Vision API containing large images fail when GZipped.
                annotateRequest.setDisableGZipContent(true);
                Log.d(TAG, "created Cloud Vision request object, sending request");

                BatchAnnotateImagesResponse response = annotateRequest.execute();
                return convertResponseToString(response);

            } catch (GoogleJsonResponseException e) {
                Log.d(TAG, "failed to make API request because " + e.getContent());
            } catch (Throwable e) {
                Log.d(TAG, "failed to make API request because of " + e.getMessage());
            }
            return "Cloud Vision API request failed. Check logs for details.";
        }

        /**
         * @param response
         * @return
         */
        private String convertResponseToString(BatchAnnotateImagesResponse response) {
            String message = "";

            List<EntityAnnotation> labels = response.getResponses().get(0).getTextAnnotations();
            if (labels != null) {
                for (EntityAnnotation label : labels) {
                    message += String.format("%s", label.getDescription());
                }
            }

            return message;
        }

        protected void onPostExecute(String result) {
            //mImageDetails.setText(result);
            Log.i(TAG, "RESULT " + result);
            NotesDbAdapter dbHelper = null;
            try {
                dbHelper = new NotesDbAdapter(getActivity());
                dbHelper.open();
                Note newNote = new Note();
                newNote.id = Utils.extractRowIdFromFileName(imageAbsolutePath);
                newNote.textExtract = result;
                dbHelper.createNote(newNote);

                //TODO: upload to cloud

                try {
                    HttpTransport httpTransport = new NetHttpTransport();
                    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new MyInitializer());
                    GenericUrl genericUrl = new GenericUrl(Configuration.DROPBOX_URL);

                    //Get the upload URL from server
                    HttpRequest httpGetRequest = requestFactory.buildGetRequest(genericUrl);
                    HttpResponse httpGetResponse = httpGetRequest.execute();
                    Log.i(TAG, "HTTP STATUS:: " + httpGetResponse.getStatusCode());

                    if (httpGetResponse.getStatusCode() == 200) {
                        //MyUrl myUrl = null;
                        JSONObject getJson = null;

                        try {
                            // process the HTTP response object
                            String response = httpGetResponse.parseAsString();
                            Log.i(TAG, "URL:: " + response);
                            getJson = new JSONObject(response);
                        } finally {
                            httpGetResponse.disconnect();
                        }

                        //upload the image
                        {
                            Map<String, String> parameters = Maps.newHashMap();
                            parameters.put("rowId", String.valueOf(newNote.id));

                            // Add parameters
                            MultipartContent content = new MultipartContent()
                                    .setMediaType(new HttpMediaType("multipart/form-data")
                                            .setParameter("boundary", "__END_OF_PART__"));

                            for (String name : parameters.keySet()) {
                                MultipartContent.Part part = new MultipartContent.Part(
                                        new ByteArrayContent(null, parameters.get(name).getBytes()));
                                part.setHeaders(new HttpHeaders().set("Content-Disposition",
                                        String.format("form-data; name=\"%s\"", name)));
                                content.addPart(part);
                            }

                            // Add file
                            FileContent fileContent = new FileContent("image/jpeg",
                                    new File(imageAbsolutePath));
                            MultipartContent.Part part = new MultipartContent.Part(fileContent);
                            part.setHeaders(new HttpHeaders().set("Content-Disposition", String
                                    .format("form-data; name=\"file\"; filename=\"%s\"", imageAbsolutePath)));
                            content.addPart(part);

                            HttpResponse httpPostResponse = null;

                            try {
                                httpPostResponse = requestFactory
                                        .buildPostRequest(new GenericUrl(getJson.getString("url")), content)
                                        .execute();

                                Log.i(TAG, "HTTP STATUS:: " + httpPostResponse.getStatusCode());
                                // process the HTTP response object
                                String response = httpPostResponse.parseAsString();
                                Log.i(TAG, "URI:: " + response);
                                JSONObject postJson = new JSONObject(response);

                                //update the uri in the database
                                Note updatedNote = new Note();
                                updatedNote.id = newNote.id;
                                updatedNote.uri = postJson.getString("uri");
                                dbHelper.updateNote(updatedNote);

                            } finally {
                                httpPostResponse.disconnect();
                            }
                        }
                        //upload the Note Json to the server. It now has the URI to the image,and textextract
                        {
                            JSONObject jsonObject = new JSONObject();

                            Note note = dbHelper.fetchNote(newNote.id);
                            jsonObject.put("rowId", note.id);
                            jsonObject.put("beer", note.beer);
                            jsonObject.put("rating", note.rating);
                            jsonObject.put("textExtract", note.textExtract);
                            jsonObject.put("notes", note.notes);
                            jsonObject.put("uri", note.uri);
                            jsonObject.put("timeCreatedMs", note.created);
                            jsonObject.put("timeCreatedTimeZoneOffsetMs", TimeZone.getDefault().getRawOffset());
                            jsonObject.put("timeUpdatedMs", note.updated);
                            jsonObject.put("timeUpdatedTimeZoneOffsetMs", TimeZone.getDefault().getRawOffset());

                            HttpResponse httpPostResponse = null;

                            try {
                                httpPostResponse = requestFactory
                                        .buildPostRequest(new GenericUrl(Configuration.CONTENTS_URL),
                                                new ByteArrayContent("application/json",
                                                        jsonObject.toString().getBytes()))
                                        .execute();

                                Log.i(TAG, "HTTP STATUS:: " + httpPostResponse.getStatusCode());

                            } finally {
                                httpPostResponse.disconnect();
                            }
                        }

                    }

                } catch (Throwable e) {
                    Log.e(TAG, e.getMessage(), e);
                }

                //                    long BACKOFF = Configuration.HTTP_BACKOFF_MS
                //                            + new Random().nextInt(Configuration.HTTP_BACKOFF_MS);
                //                    int MAX_ATTEMPTS = Configuration.HTTP_MAX_ATTEMPTS;
                //                    int CONNECTION_TIMEOUT = Configuration.HTTP_CONNECTION_TIMEOUT;
                //                    int SOCKET_TIMEOUT = Configuration.HTTP_SOCKET_TIMEOUT;
                //                    int[] validResponseCodes = {200};
                //
                //                    for (int j = 1; j <= MAX_ATTEMPTS; j++) {
                //                        Log.d(TAG, "Attempt #" + j + " to upload content");
                //                        try {
                //                            Log.d(TAG, "Entering");
                //                            // wait for network connectivity; will download the content list
                //                            // over cellular network
                //                            int lStatusCode = Utils.retryIfNetworkDisconnected(mConnectivityManager);
                //                            if (lStatusCode == StatusCode.NETWORK_DISCONNECTED)
                //                                break;
                //
                //                            HashMap<String, String> params = new HashMap<String, String>();
                //                            params.put("id", String.valueOf(note.id));
                //
                //                            String responseJson = HttpUtils.doHttpGet(Configuration.DROPBOX_URL, CONNECTION_TIMEOUT, SOCKET_TIMEOUT, validResponseCodes);
                //
                //                            JSONObject jsonObject = new JSONObject(responseJson);
                //                            String url = jsonObject.getString("url");
                //                            Log.d(TAG, "URL: " + url);
                //                            String uri = HttpUtils.doMultiPartHttpPost(url,
                //                                    imageAbsolutePath,
                //                                    CONNECTION_TIMEOUT,
                //                                    SOCKET_TIMEOUT, validResponseCodes);
                //                            Log.d(TAG, "URI: " + uri);
                //                            JSONObject jsonObject1 = new JSONObject();
                //                            jsonObject1.put("id", note.id);
                //                            jsonObject1.put("uri", uri);

                //                            HttpUtils.doHttpPost(Configuration.CONTENTS_URL, jsonObject1, "application/json", CONNECTION_TIMEOUT, SOCKET_TIMEOUT, validResponseCodes);

                // success
                //                            j = MAX_ATTEMPTS;
                //                        } catch (ClientProtocolException e) {
                //                            Log.e(TAG, e.getMessage(), e);
                //                        } catch (IOException e) {
                //                            Log.e(TAG, "IOException on attempt " + j, e);
                //                            if (j == MAX_ATTEMPTS) {
                //                                break;
                //                            }
                //                            try {
                //                                Log.d(TAG, "Sleeping for " + BACKOFF
                //                                        + " ms before retry");
                //                                Thread.sleep(BACKOFF);
                //                            } catch (InterruptedException e1) {
                //                                // Activity finished
                //                                // before we
                //                                // complete - exit.
                //                                Log.d(TAG, "Thread interrupted: abort remaining retries!");
                //                                Thread.currentThread().interrupt();
                //                            }
                //                            // increase backoff
                //                            // exponentially
                //                            BACKOFF *= 2;
                //
                //                        } catch (StatusCodeException e) {
                //                            Log.e(TAG, e.getMessage(), e);
                //                            if (e.getStatusCode() == 503) {
                //                                Log.e(TAG, "Failed to upload on attempt " + j, e);
                //                                if (j == MAX_ATTEMPTS) {
                //                                    break;
                //                                }
                //                                try {
                //                                    Log.d(TAG, "Sleeping for " + BACKOFF
                //                                            + " ms before retry");
                //                                    Thread.sleep(BACKOFF);
                //                                } catch (InterruptedException e1) {
                //                                    // Activity finished before we complete - exit.
                //                                    Log.d(TAG, "Thread interrupted: abort remaining retries!");
                //                                    Thread.currentThread().interrupt();
                //                                }
                //                                // increase backoff exponentially
                //                                BACKOFF *= 2;
                //                            } else {
                //                                break;
                //                            }
                //                        } finally {
                //                            Log.d(TAG, "Exiting");
                //
                //                        }
                //                    }

            } catch (Throwable e) {
                android.util.Log.e(TAG,
                        "error: " + ((e.getMessage() != null) ? e.getMessage().replace(" ", "_") : ""), e);
            } finally {
                if (dbHelper != null)
                    dbHelper.close();
            }

        }

    }.execute();
}

From source file:com.firefly.sample.castcompanionlibrary.cast.player.VideoCastControllerFragment.java

private void showImage(final String url) {
    if (null != mImageAsyncTask) {
        mImageAsyncTask.cancel(true);//from  w w  w  .  ja v a  2s  .  c  o  m
    }
    if (null == url) {
        mCastController.setImage(
                BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.dummy_album_art_large));
        return;
    }
    if (null != mUrlAndBitmap && mUrlAndBitmap.isMatch(url)) {
        // we can reuse mBitmap
        mCastController.setImage(mUrlAndBitmap.mBitmap);
        return;
    }
    mUrlAndBitmap = null;
    mImageAsyncTask = new AsyncTask<String, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(String... params) {
            String uri = params[0];
            try {
                URL imgUrl = new URL(uri);
                return BitmapFactory.decodeStream(imgUrl.openStream());
            } catch (Exception e) {
                LOGE(TAG, "Failed to load the image with mUrl: " + uri, e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (null != bitmap) {
                mUrlAndBitmap = new UrlAndBitmap();
                mUrlAndBitmap.mBitmap = bitmap;
                mUrlAndBitmap.mUrl = url;
                mCastController.setImage(bitmap);
            }
        }
    };

    mImageAsyncTask.execute(url);
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

protected Task<Map<String, RateLimitStatus>> doCheckStatus(final Twitter instance) {
    final Task<Map<String, RateLimitStatus>>.TaskCompletionSource source = Task.create();

    new AsyncTask<Void, Void, Object>() {

        @Override/* www. ja va  2s  . co  m*/
        protected Object doInBackground(Void... params) {
            try {
                return instance.getRateLimitStatus();
            } catch (TwitterException e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o instanceof Map) {
                source.trySetResult((Map<String, RateLimitStatus>) o);
            } else {
                source.trySetError((Exception) o);
            }

        }
    }.execute();
    return source.getTask();
}

From source file:org.anhonesteffort.flock.SubscriptionGoogleFragment.java

private void handleRefreshDaysTillCharge() {
    if (recurringTask != null)
        return;/* w  w  w. java  2 s  .  c o m*/

    recurringTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleRefreshDaysTillCharge");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();

            if (subscriptionActivity.billingService == null) {
                Log.e(TAG, "billing service is null");
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
                return result;
            }

            try {

                Bundle ownedItems = subscriptionActivity.billingService.getPurchases(3,
                        SubscriptionGoogleFragment.class.getPackage().getName(), PRODUCT_TYPE_SUBSCRIPTION,
                        null);

                ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                for (int i = 0; i < purchaseDataList.size(); ++i) {
                    JSONObject productObject = new JSONObject(purchaseDataList.get(i));
                    if (productObject.getString("productId").equals(SKU_YEARLY_SUBSCRIPTION)) {
                        long purchaseTime = productObject.getLong("purchaseTime");
                        long msSincePurchase = new Date().getTime() - purchaseTime;
                        if (msSincePurchase < 0)
                            msSincePurchase = 0;

                        daysTillNextCharge = 365 - (msSincePurchase / 1000 / 60 / 60 / 24);
                        if (daysTillNextCharge < 0)
                            daysTillNextCharge = 0;
                    }
                }

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (RemoteException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            } catch (JSONException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            recurringTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS)
                handleUpdateUi();
            else
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
        }
    }.execute();
}