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:bbct.android.common.activity.BaseballCardDetails.java

@SuppressLint("StaticFieldLeak")
private void populateTextEdits() {
    Bundle args = getArguments();/*from   w  ww .  jav a 2  s .c  o m*/
    if (args != null) {
        id = args.getLong(ID);
        new AsyncTask<Long, Void, BaseballCard>() {
            @Override
            protected BaseballCard doInBackground(Long... args) {
                long id = args[0];
                BaseballCardDatabase database = BaseballCardDatabase.getInstance(getActivity());
                BaseballCardDao dao = database.getBaseballCardDao();
                return dao.getBaseballCard(id);
            }

            @Override
            protected void onPostExecute(BaseballCard card) {
                setCard(card);
            }
        }.execute(id);
    }
}

From source file:com.example.snapcacheexample.SelectionFragment.java

private void handleAnnounce() {
    pendingAnnounce = false;/*from  w  w w. j a va2  s.  co  m*/
    Session session = Session.getActiveSession();

    if (session == null || !session.isOpened()) {
        return;
    }

    List<String> permissions = session.getPermissions();
    if (!permissions.containsAll(PERMISSIONS)) {
        pendingAnnounce = true;
        requestPublishPermissions(session);
        return;
    }

    // Show a progress dialog because sometimes the requests can take a while.
    progressDialog = ProgressDialog.show(getActivity(), "",
            getActivity().getResources().getString(R.string.progress_dialog_text), true);

    // Run this in a background thread since some of the populate methods may take
    // a non-trivial amount of time.
    AsyncTask<Void, Void, Response> task = new AsyncTask<Void, Void, Response>() {

        @Override
        protected Response doInBackground(Void... voids) {
            EatAction eatAction = GraphObject.Factory.create(EatAction.class);
            for (BaseListElement element : listElements) {
                element.populateOGAction(eatAction);
            }
            Request request = new Request(Session.getActiveSession(), POST_ACTION_PATH, null, HttpMethod.POST);
            request.setGraphObject(eatAction);
            return request.executeAndWait();
        }

        @Override
        protected void onPostExecute(Response response) {
            onPostActionResponse(response);
        }
    };

    task.execute();
}

From source file:com.silentcircle.silenttext.activity.AccountCreationActivity.java

@Override
public void onFinish(final Bundle arguments) {

    if (!tasks.isEmpty()) {
        return;/*from  ww  w . j  a  va  2 s .  c  om*/
    }

    tasks.add(AsyncUtils.execute(new AsyncTask<Void, Void, UsernamePasswordCredential>() {

        @Override
        protected UsernamePasswordCredential doInBackground(Void... params) {

            UserManager manager = SilentTextApplication.from(getActivity()).getUserManager();

            BasicUser user = new BasicUser();

            user.setFirstName(arguments.getCharSequence(AccountCreationFragment.EXTRA_FIRST_NAME));
            user.setLastName(arguments.getCharSequence(AccountCreationFragment.EXTRA_LAST_NAME));
            user.setEmailAddress(arguments.getCharSequence(AccountCreationFragment.EXTRA_EMAIL));

            CharSequence username = arguments.getCharSequence(AccountCreationFragment.EXTRA_USERNAME);
            CharSequence password = arguments.getCharSequence(AccountCreationFragment.EXTRA_PASSWORD);
            CharSequence licenseCode = arguments.getCharSequence(AccountCreationFragment.EXTRA_LICENSE_CODE);

            try {
                UsernamePasswordCredential credential = new UsernamePasswordCredential(username, password);
                manager.createUser(credential, user, licenseCode);
                return credential;
            } catch (HTTPException e) {
                onError(e);
            } catch (Throwable t) {
                onError(t);
            }
            return null;
        }

        protected void onError(HTTPException e) {
            try {
                String errorString = new String();
                JSONObject errorJSON = new JSONObject(e.getBody());

                if (errorJSON.has("error_fields")) {
                    JSONObject errorFieldsJSON = errorJSON.getJSONObject("error_fields");

                    if (errorFieldsJSON.length() > 0) {
                        if (errorFieldsJSON.has("license_code")) {
                            errorString = errorFieldsJSON.getJSONObject("license_code").getString("error_msg");
                        } else {
                            if (!StringUtils.isEmpty(
                                    JSONObjectParser.parseFault(JSONParser.parse(e.getBody())).getFields()[0]
                                            .getMessage())) {
                                errorString = JSONObjectParser.parseFault(JSONParser.parse(e.getBody()))
                                        .getFields()[0].getMessage().toString();
                            }
                        }
                    } else {
                        if (!StringUtils.isEmpty(errorJSON.getString("error_msg"))) {
                            errorString = errorJSON.getString("error_msg");
                        }
                    }
                }

                AccountCreationActivity.this.onError(errorString);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        protected void onError(Throwable t) {
            AccountCreationActivity.this.onError(t.getLocalizedMessage());
        }

        @Override
        protected void onPostExecute(UsernamePasswordCredential credential) {
            tasks.clear();

            if (credential != null) {
                activate(credential);
                credential.burn();
            }
        }

        @Override
        protected void onPreExecute() {
            Toast.makeText(getActivity(), getString(R.string.creating_account), Toast.LENGTH_LONG).show();
        }

    }));

}

From source file:com.clover.android.sdk.examples.InventoryTestActivity.java

private void connectToInventoryWebService() {
    new AsyncTask<Void, Void, Void>() {
        @Override//from   w  w  w  .j  a  v a2 s  .c o m
        protected Void doInBackground(Void... params) {
            try {
                Account account = CloverAccount.getAccount(InventoryTestActivity.this);
                CloverAuth.AuthResult authResult = CloverAuth.authenticate(InventoryTestActivity.this, account);
                String baseUrl = authResult.authData.getString(CloverAccount.KEY_BASE_URL);

                if (authResult.authToken != null && baseUrl != null) {
                    CustomHttpClient httpClient = CustomHttpClient.getHttpClient();
                    String getNameUri = "/v2/merchant/name";
                    String url = baseUrl + getNameUri + "?access_token=" + authResult.authToken;
                    String result = httpClient.get(url);
                    JSONTokener jsonTokener = new JSONTokener(result);
                    JSONObject root = (JSONObject) jsonTokener.nextValue();
                    String merchantId = root.getString("merchantId");
                    inventoryService = new InventoryWebService(merchantId, authResult.authToken, baseUrl);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error retrieving merchant info from server", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (inventoryService != null) {
                statusText.setText("using web service");
                serviceIsBound = true;
                fetchItemsFromService();
            } else {
                statusText.setText("failed to connect to web service");
            }
        }
    }.execute();
}

From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java

private void runHttpURLConnection() {
    final String url = urlEdit.getText().toString();
    if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
        list.add("URL error!");
        adapter.notifyDataSetChanged();//  www . ja  v a2 s  .  co  m
        return;
    }
    task = new AsyncTask<Void, Integer, Void>() {
        long startTime;
        ProgressDialog progress;

        // ??
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progress = new ProgressDialog(SpeedTestActivity.this);
            progress.setMessage(getString(R.string.progress_message));
            progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progress.setIndeterminate(false);
            progress.setCancelable(true);
            progress.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    task.cancel(true);
                }
            });
            progress.setMax(10);
            progress.setProgress(0);
            progress.show();

            startTime = System.currentTimeMillis();
        }

        // ???
        @Override
        protected Void doInBackground(Void... params) {
            // 10?????
            for (int i = 0; i < 10; i++) {
                HttpURLConnection connection = null;
                InputStreamReader in = null;
                // BufferedReader br = null;
                try {
                    connection = (HttpURLConnection) (new URL(url)).openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    in = new InputStreamReader(connection.getInputStream());
                    // br = new BufferedReader(in);
                    // while (br.readLine() != null) {
                    long len = 0;
                    while (in.read() != -1) {
                        len++;
                    }
                    Log.i("HttpURLConnection", len + " Bytes");
                } catch (IOException e) {
                } finally {
                    /*
                     * if (br != null) { try { br.close(); } catch
                     * (IOException e) { } br = null; }
                     */
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                        in = null;
                    }
                    if (connection != null) {
                        connection.disconnect();
                        connection = null;
                    }
                }
                publishProgress(i + 1);
                // Dos????????
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (progress == null) {
                return;
            }
            progress.setProgress(values[0]);
        }

        // 
        @Override
        protected void onPostExecute(Void result) {
            long endTime = System.currentTimeMillis();

            // 
            progress.cancel();
            progress = null;

            list.add("HttpURLConnection:" + url + " " + (endTime - startTime) + "msec/10" + " "
                    + (endTime - startTime) / 10 + "msec");
            adapter.notifyDataSetChanged();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            progress.dismiss();
            progress = null;
        }
    }.execute();
}

From source file:ca.rmen.android.poetassistant.main.dictionaries.search.Search.java

/**
 * Adds the given suggestions to the search history, in a background thread.
 *///from  w  w w  .  j a v  a 2  s  .  c  o m
@MainThread
public void addSuggestions(String... suggestions) {
    new AsyncTask<String, Void, Void>() {

        @Override
        protected Void doInBackground(String... searchTerms) {
            ContentValues[] contentValues = new ContentValues[suggestions.length];
            for (int i = 0; i < suggestions.length; i++) {
                ContentValues contentValue = new ContentValues(1);
                contentValue.put(SearchManager.QUERY, suggestions[i]);
                contentValues[i] = contentValue;
            }
            mContext.getContentResolver().bulkInsert(SuggestionsProvider.CONTENT_URI, contentValues);
            return null;
        }
    }.execute(suggestions);
}

From source file:com.adisayoga.earthquake.ui.SocialConnectActivity.java

/**
 * Tampilkan informasi Twitter sebagai tanda sudah login/belum.
 *///from ww  w  .jav a  2s .c  o  m
private void showTwitterInfo() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            publishProgress();
            return twitter.getScreenName();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            twitterLoginStatus.setText(R.string.loading);
        }

        @Override
        protected void onPostExecute(String result) {
            twitterLoginStatus.setText(getText(R.string.welcome) + " " + result);
        }

    }.execute();
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.SystemMonitor.java

private void publishResult(Location loc) {
    String t = getTimestamp() + "\n";
    t += "Longitude:" + loc.getLongitude() + "\n";
    t += "Latitude:" + loc.getLatitude() + "\n";
    t += "BatteryPercent: " + batteryPercent + "\n";
    t += "-----------------------------------------";

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("personal", Context.MODE_PRIVATE);

    phoneNr = prefs.getString(getString(R.string.p_emcy_phone_nr), "");

    // TODO: check Internet State before sending

    // send message to server
    JSONArray jsa = new JSONArray();
    JSONObject jso = new JSONObject();
    try {//from ww w. jav a2s .c  o  m
        jso.put("Timestamp", getTimestamp());
        jso.put("Longitude", loc.getLongitude());
        jso.put("Latitude", loc.getLatitude());
        jso.put("PercentBattery", batteryPercent);
        jsa.put(jso);
        sendNotification(jsa);
    } catch (JSONException e) {
        Log.e(SystemMonitor.class.getSimpleName(), e.getLocalizedMessage());
    }

    // send message to a gmail acc
    new AsyncTask<String, Void, Void>() {

        @Override
        protected Void doInBackground(String... params) {
            //            String message = params[0];
            // GMailSender sender = new GMailSender(
            // null,
            // null);
            // try {
            // sender.sendMail("myHealthAssistant: SystemMonitor",
            // message,
            // null,
            // null);
            // } catch (Exception e) {
            // Log.e(SystemMonitor.class.getSimpleName(), e.getMessage());
            // }
            return null;
        }

    }.execute(t, null, null);

}