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.afrozaar.jazzfestreporting.MainActivity.java

private void loadUploadedVideos() {
    if (mChosenAccountName == null) {
        return;//from ww  w  .  j a  v a  2s.  c o m
    }

    setProgressBarIndeterminateVisibility(true);
    new AsyncTask<Void, Void, List<VideoData>>() {
        @Override
        protected List<VideoData> doInBackground(Void... voids) {

            YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential)
                    .setApplicationName(Constants.APP_NAME).build();

            try {
                /*
                 * Now that the user is authenticated, the app makes a
                * channels list request to get the authenticated user's
                * channel. Returned with that data is the playlist id for
                * the uploaded videos.
                * https://developers.google.com/youtube
                * /v3/docs/channels/list
                */
                ChannelListResponse clr = youtube.channels().list("contentDetails").setMine(true).execute();

                // Get the user's uploads playlist's id from channel list
                // response
                String uploadsPlaylistId = clr.getItems().get(0).getContentDetails().getRelatedPlaylists()
                        .getUploads();

                List<VideoData> videos = new ArrayList<VideoData>();

                // Get videos from user's upload playlist with a playlist
                // items list request
                PlaylistItemListResponse pilr = youtube.playlistItems().list("id,contentDetails")
                        .setPlaylistId(uploadsPlaylistId).setMaxResults(20l).execute();
                List<String> videoIds = new ArrayList<String>();

                // Iterate over playlist item list response to get uploaded
                // videos' ids.
                for (PlaylistItem item : pilr.getItems()) {
                    videoIds.add(item.getContentDetails().getVideoId());
                }

                // Get details of uploaded videos with a videos list
                // request.
                VideoListResponse vlr = youtube.videos().list("id,snippet,status")
                        .setId(TextUtils.join(",", videoIds)).execute();

                // Add only the public videos to the local videos list.
                for (Video video : vlr.getItems()) {
                    if ("public".equals(video.getStatus().getPrivacyStatus())) {
                        VideoData videoData = new VideoData();
                        videoData.setVideo(video);
                        videos.add(videoData);
                    }
                }

                // Sort videos by title
                Collections.sort(videos, new Comparator<VideoData>() {
                    @Override
                    public int compare(VideoData videoData, VideoData videoData2) {
                        return videoData.getTitle().compareTo(videoData2.getTitle());
                    }
                });

                return videos;

            } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
                showGooglePlayServicesAvailabilityErrorDialog(availabilityException.getConnectionStatusCode());
            } catch (UserRecoverableAuthIOException userRecoverableException) {
                startActivityForResult(userRecoverableException.getIntent(), REQUEST_AUTHORIZATION);
            } catch (IOException e) {
                Utils.logAndShow(MainActivity.this, Constants.APP_NAME, e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<VideoData> videos) {
            setProgressBarIndeterminateVisibility(false);

            if (videos == null) {
                return;
            }

            mUploadsListFragment.setVideos(videos);
        }

    }.execute((Void) null);
}

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

private void handleCancelSubscription() {
    if (asyncTask != null)
        return;/* w  w w.j  a v  a2 s  .  co 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.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) {
                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:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Export data.// w  w w. j av a  2s .c o  m
 * 
 * @param descr
 *            description of the exported rule set
 * @param fn
 *            one of the predefined file names from {@link DataProvider}.
 */
private void exportData(final String descr, final String fn) {
    if (descr == null) {
        final EditText et = new EditText(this);
        Builder builder = new Builder(this);
        builder.setView(et);
        builder.setCancelable(true);
        builder.setTitle(R.string.export_rules_descr);
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                Preferences.this.exportData(et.getText().toString(), fn);
            }
        });
        builder.show();
    } else {
        final ProgressDialog d = new ProgressDialog(this);
        d.setIndeterminate(true);
        d.setMessage(this.getString(R.string.export_progr));
        d.setCancelable(false);
        d.show();

        // run task in background
        final AsyncTask<Void, Void, String> task = // .
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(final Void... params) {
                        if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                            return DataProvider.backupRuleSet(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                            return DataProvider.backupLogs(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                            return DataProvider.backupNumGroups(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                            return DataProvider.backupHourGroups(Preferences.this, descr);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final String result) {
                        Log.d(TAG, "export:\n" + result);
                        System.out.println("\n" + result);
                        d.dismiss();
                        if (result != null && result.length() > 0) {
                            Uri uri = null;
                            int resChooser = -1;
                            if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                                uri = DataProvider.EXPORT_RULESET_URI;
                                resChooser = R.string.export_rules_;
                            } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                                uri = DataProvider.EXPORT_LOGS_URI;
                                resChooser = R.string.export_logs_;
                            } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_NUMGROUPS_URI;
                                resChooser = R.string.export_numgroups_;
                            } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_HOURGROUPS_URI;
                                resChooser = R.string.export_hourgroups_;
                            }
                            final Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType(DataProvider.EXPORT_MIMETYPE);
                            intent.putExtra(Intent.EXTRA_STREAM, uri);
                            intent.putExtra(Intent.EXTRA_SUBJECT, // .
                                    "Call Meter 3G export");
                            intent.addCategory(Intent.CATEGORY_DEFAULT);

                            try {
                                final File d = Environment.getExternalStorageDirectory();
                                final File f = new File(d, DataProvider.PACKAGE + File.separator + fn);
                                f.mkdirs();
                                if (f.exists()) {
                                    f.delete();
                                }
                                f.createNewFile();
                                FileWriter fw = new FileWriter(f);
                                fw.append(result);
                                fw.close();
                                // call an exporting app with the uri to the
                                // preferences
                                Preferences.this.startActivity(
                                        Intent.createChooser(intent, Preferences.this.getString(resChooser)));
                            } catch (IOException e) {
                                Log.e(TAG, "error writing export file", e);
                                Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    }
                };
        task.execute((Void) null);
    }
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

@Override
public void showDialog(final Context context, String action, Map<String, String> parameters,
        final CallbackListener listener, final boolean isCancelable) {

    Uri uri = Uri.parse(Constants.GRAPH_BASE_URL);
    android.net.Uri.Builder builder = uri.buildUpon();
    builder.appendEncodedPath("dialog" + action);
    for (Entry<String, String> param : parameters.entrySet()) {
        builder.appendQueryParameter(param.getKey(), param.getValue());
    }/*from w ww . java 2 s . c om*/
    final String url = builder.build().toString();
    AsyncTask<String, Void, Void> tasc = new AsyncTask<String, Void, Void>() {
        private Exception e;

        @Override
        protected Void doInBackground(String... params) {
            try {
                refreshToken();
            } catch (RemoteException e) {
                this.e = e;
            } catch (ApiException e) {
                this.e = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void res) {
            if (e == null) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("oauth_token", getAccessToken());
                new MixiDialog(context, url, map, listener, isCancelable).show();
            } else {
                Log.v(TAG, "refresh token error");
                listener.onFatal(new ErrorInfo(e));
            }
        }
    };
    tasc.execute(url);
}

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

public void markWonLost(final String type, final ODataRow record, final OnOperationSuccessListener listener) {
    new AsyncTask<Void, Void, Void>() {
        private ProgressDialog dialog;

        @Override/*from  w  w  w.j av a2s  .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) {
            _markWonLost(type, record);
            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:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ???./*from  w  w  w.  j a  v  a2s . c o  m*/
 * 
 * @param deviceId ?ID
 * @param sessionKey ID
 * @param listener 
 */
public static void asyncRegisterOnDataAvaible(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();
                HttpPut request = new HttpPut(
                        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:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java

public void onClickOkSaveMapDialog(final String mapName) {
    assert (mapName != null && !mapName.isEmpty());
    mSaveMapButton.setEnabled(false);/* w  ww  .j a v  a  2 s .  c  om*/
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            mTangoServiceClientNode.callSaveMapService(mapName);
            return null;
        }
    }.execute();
}

From source file:com.upnext.blekit.BLEKit.java

private static void fetchJsonLocal() {
    L.d(".");/*w  w  w  .j a va2s  . co  m*/
    AsyncTask<String, Void, JsonNode> task = new AsyncTask<String, Void, JsonNode>() {

        @Override
        protected JsonNode doInBackground(String... params) {
            L.d("fetching from " + params[0]);
            HttpClient client = new HttpClient(params[0]);
            Response<JsonNode> response = client.get(JsonNode.class, null);
            return response.getBody();
        }

        @Override
        protected void onPostExecute(JsonNode s) {
            L.d("fetched " + s);
            if (s != null) {
                mCurrentZone = jsonParser.parse(s + "");
            }
        }
    };
    task.execute(jsonUrl);
}

From source file:com.df.push.DemoActivity.java

private void unsubscribe(final String topic) {
    final String url = "https://next.cloud.dreamfactory.com/rest/sns/subscription/" + topic
            + "?app_name=todoangular";

    new AsyncTask<Void, Void, String>() {
        @Override/* ww  w. j a  v  a 2 s . c o m*/
        protected String doInBackground(Void... params) {
            String msg = "";

            HttpResponse<JsonNode> jsonResponse;
            try {
                jsonResponse = Unirest.delete(url).header("accept", "application/json").asJson();
                msg = "Unsubscribe response " + jsonResponse.getBody().toString();
                Log.i(TAG, msg);
                subscriptions.remove(topic);
            } catch (UnirestException e) {
                msg = e.getLocalizedMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
            progressDialog.dismiss();
            subscriptions.remove(topic);
        }

        @Override
        protected void onPreExecute() {
            if (progressDialog != null)
                progressDialog.show();
        };
    }.execute(null, null, null);
}