List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:ar.com.tristeslostrestigres.diasporanativewebapp.services.GetPodsService.java
private void getPods() { /*/*from w ww . j av a 2 s . c o m*/ * Most of the code in this AsyncTask is from the file getPodlistTask.java * from the app "Diaspora Webclient". * A few modifications and adaptations were made by me. * Source: * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java * Thanks to Terkel Srensen */ AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() { @Override protected String[] doInBackground(Void... params) { // TODO: Update deprecated code StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); List<String> list = null; try { HttpGet httpGet = new HttpGet("http://podupti.me/api.php?key=4r45tg&format=json"); HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { //TODO Notify User about failure Log.e(TAG, "Failed to download list of pods"); } } catch (IOException e) { //TODO handle json buggy feed e.printStackTrace(); } //Parse the JSON Data try { JSONObject j = new JSONObject(builder.toString()); JSONArray jr = j.getJSONArray("pods"); Log.d(TAG, "Number of entries " + jr.length()); list = new ArrayList<String>(); for (int i = 0; i < jr.length(); i++) { JSONObject jo = jr.getJSONObject(i); Log.d(TAG, jo.getString("domain")); String secure = jo.getString("secure"); if (secure.equals("true")) list.add(jo.getString("domain")); } } catch (Exception e) { //TODO Handle Parsing errors here e.printStackTrace(); } if (list != null) return list.toArray(new String[list.size()]); else return null; } @Override protected void onPostExecute(String[] strings) { Intent broadcastIntent = new Intent(MESSAGE); if (strings != null) broadcastIntent.putExtra("pods", strings); sendBroadcast(broadcastIntent); stopSelf(); } }; getPodsAsync.execute(); }
From source file:com.blork.anpod.util.BitmapUtils.java
/** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param context the context// w w w. ja v a2 s .co m * @param desiredHeight * @param desiredWidth * @param url the url * @param name the name * @param decodeOptions the decode options * @param cookie An arbitrary object that will be passed to the callback. * @param callback the callback */ public static void fetchImage(final Context context, final Picture picture, final int desiredWidth, final int desiredHeight, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, BitmapResult>() { @Override protected BitmapResult doInBackground(String... params) { BitmapResult result = fetchImage(context, picture, desiredWidth, desiredHeight); return result; } @Override protected void onPostExecute(BitmapResult result) { callback.onFetchComplete(result); } }.execute(picture.getFullSizeImageUrl()); }
From source file:com.socialize.auth.twitter.TwitterOAuthProvider.java
public void retrieveRequestTokenAsync(final OAuthConsumer consumer, final String callbackUrl, final OAuthRequestTokenUrlListener listener) { new AsyncTask<Void, Void, Void>() { String url;/*w w w.j av a 2 s. co m*/ Exception error; @Override protected Void doInBackground(Void... params) { try { url = retrieveRequestToken(consumer, callbackUrl); } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(Void result) { if (listener != null) { if (error != null) { listener.onError(error); } else { listener.onRequestUrl(url); } } } }.execute(); }
From source file:com.example.m.niceproject.service.WeatherCacheService.java
public void load(final WeatherServiceListener listener) { new AsyncTask<WeatherServiceListener, Void, Channel>() { private WeatherServiceListener weatherListener; @Override/* www .j a v a2 s .com*/ protected Channel doInBackground(WeatherServiceListener[] serviceListeners) { weatherListener = serviceListeners[0]; try { FileInputStream inputStream = context.openFileInput(CACHED_WEATHER_FILE); StringBuilder cache = new StringBuilder(); int content; while ((content = inputStream.read()) != -1) { cache.append((char) content); } inputStream.close(); JSONObject jsonCache = new JSONObject(cache.toString()); Channel channel = new Channel(); channel.populate(jsonCache); return channel; } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(Channel channel) { if (channel == null && error != null) { weatherListener.serviceFailure(error); } else { weatherListener.serviceSuccess(channel); } } }.execute(listener); }
From source file:mc.lib.network.AsyncNetworkHelper.java
public static void getDrawable(final String url, final OnCompleteListener<Drawable> listener) { new AsyncTask<Void, Void, Drawable>() { @Override/*from www . j ava 2 s. c o m*/ protected Drawable doInBackground(Void... params) { return NetworkHelper.getDrawable(url); } @Override protected void onPostExecute(Drawable res) { super.onPostExecute(res); listener.complete(res); } }.execute((Void) null); }
From source file:com.koodroid.chicken.KooDroidHelper.java
public void checkForUpdateOnBackgroundThread(final MainActivity activity) { if (mAlreadyCheckedForUpdates) { return;/*ww w . jav a 2 s . c o m*/ } mAlreadyCheckedForUpdates = true; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { SharedPreferences prefs = activity.getSharedPreferences(KooDroidHelper.class.getName(), Context.MODE_PRIVATE); Random random = new Random(); long interval = random.nextInt(7) + 3; // [3, 10) long timestamp = prefs.getLong("LastCheckTimestamp", 0); long now = System.currentTimeMillis(); if ((now - timestamp < interval * 24 * 60 * 60 * 1000) && !DEBUG) { return null; } prefs.edit().putLong("LastCheckTimestamp", now).commit(); HttpURLConnection urlConnection = null; BufferedReader in = null; try { URL url = new URL(mUpdateUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(60000); urlConnection.setReadTimeout(60000); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("GET"); urlConnection.connect(); if (urlConnection.getResponseCode() == 200) { InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream()); in = new BufferedReader(reader); StringBuilder response = new StringBuilder(); for (String line = in.readLine(); line != null; line = in.readLine()) { response.append(line); } try { JSONObject jsonObj = new JSONObject(response.toString()); mLatestVersion = jsonObj.getString("version_code"); mDownloadUrl = jsonObj.getString("download_url"); } catch (JSONException e) { System.out.println("Json parse error"); e.printStackTrace(); } // // JSONTokener jsonParser = new JSONTokener(response.toString()); // // ?json?JSONObject // // ??"name" : nextValue"yuanzhifei89"String // JSONObject person = (JSONObject) jsonParser.nextValue(); // // ?JSON? // person.getJSONArray("phone"); // person.getString("name"); // person.getInt("age"); // person.getJSONObject("address"); // person.getBoolean("married"); // //mLatestVersion = response.toString(); int versionCode = Integer.valueOf(mLatestVersion); mUpdateAvailable = Integer.valueOf(mLatestVersion) > Integer .valueOf(getPackageVersionCode(activity)); } } catch (Exception e) { } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { } } } return null; } @Override protected void onPostExecute(Void result) { //maybeShowUpdateDialog(activity); } }.execute(); }
From source file:ch.gianulli.trelloapi.Card.java
/** * Moves this card to a different list. Attention: this operation does not update TrelloList * objects with a reference to this card. * <p/>//from w w w .jav a 2 s. c o m * This operation is asynchronous and handles errors itself. * * @param api * @param listId */ public void moveToListAsync(final TrelloAPI api, final String listId) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... voids) { try { LinkedHashMap<String, String> args = new LinkedHashMap<>(); args.put("value", listId); JSONObject result = api.makeJSONObjectRequest("PUT", "cards/" + mId + "/idList", args, true); if (result == null) { Log.i("TrelloAPI", "Error occurred when moving card: null result"); return false; } } catch (TrelloNotAccessibleException | TrelloNotAuthorizedException e) { Log.i("TrelloAPI", "Error occurred when moving card: ", e); return false; } return true; } @Override protected void onPostExecute(Boolean successful) { if (!successful) { Toast.makeText(api.getContext(), "Error: Card could not be moved.", Toast.LENGTH_LONG).show(); } } }.execute(); }
From source file:net.w3blog.uniwifi3.activity.ContactActivity.java
public void sendMessage(View v) { final String email = txtEmail.getText().toString(); final String title = txtTitle.getText().toString(); final String message = txtMessage.getText().toString(); final String id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); new AsyncTask<String, Void, Integer>() { @Override/*from w w w . j a v a2 s .c om*/ protected void onPostExecute(Integer result) { if (result == HttpStatus.SC_OK) { Toast.makeText(ContactActivity.this, R.string.send_sucess, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ContactActivity.this, R.string.send_fail, Toast.LENGTH_SHORT).show(); } } @Override protected Integer doInBackground(String... params) { final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android"); final HttpPost postRequest = new HttpPost( "http://droidpatterns.com/uniwifi/api.php?m=contact&f=post"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("email", params[0])); nameValuePairs.add(new BasicNameValuePair("title", params[1])); nameValuePairs.add(new BasicNameValuePair("message", params[2])); nameValuePairs.add(new BasicNameValuePair("id", params[3])); try { postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(postRequest); final int statusCode = response.getStatusLine().getStatusCode(); return statusCode; } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(email, title, message, id); }
From source file:com.perm.DoomPlay.LyricsDialog.java
private void getLyrics() { task = new AsyncTask<Void, Void, String>() { @Override/*from ww w.j av a2 s.c om*/ protected void onPreExecute() { super.onPreExecute(); isLoading = true; linearLoading.setVisibility(View.VISIBLE); } @Override protected String doInBackground(Void... params) { if (!MainScreenActivity.isRegister) return "For getting lyrics is necessary to sign in (vk)"; try { if (title == null) return MainScreenActivity.api.getLyrics(getArguments().getLong(keyLyricsId)); else { ArrayList<Audio> audios = MainScreenActivity.api.searchAudio(title, 1); if (audios.size() == 1 && audios.get(0).getLyrics_id() != 0) return MainScreenActivity.api.getLyrics(audios.get(0).getLyrics_id()); else { return "Sorry , can't find lyrics"; } } } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (KException e) { e.printStackTrace(); ((AbstractReceiver) getActivity()).handleKException(e); return e.getMessage(); } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); isLoading = false; linearLoading.setVisibility(View.GONE); lyrics = s; textView.setText(s); } }; task.execute(); }
From source file:eu.trentorise.smartcampus.ac.authenticator.AuthenticatorActivity.java
@Override protected void setUp() { Intent request = getIntent();//from w w w .ja v a 2 s . com String authTokenType = request.getStringExtra(Constants.KEY_AUTHORITY) != null ? request.getStringExtra(Constants.KEY_AUTHORITY) : Constants.AUTHORITY_DEFAULT; if (Constants.TOKEN_TYPE_ANONYMOUS.equals(authTokenType)) { new AsyncTask<Void, Void, UserData>() { private ProgressDialog progress = null; protected void onPostExecute(UserData result) { if (progress != null) { try { progress.cancel(); } catch (Exception e) { Log.w(getClass().getName(), "Problem closing progress dialog: " + e.getMessage()); } } if (result != null && result.getToken() != null) { getAuthListener().onTokenAcquired(result); } else { getAuthListener().onAuthFailed("Failed to create anonymous account"); } // TODO } @Override protected void onPreExecute() { progress = ProgressDialog.show(AuthenticatorActivity.this, "", AuthenticatorActivity.this.getString(R.string.auth_in_progress), true); super.onPreExecute(); } @Override protected UserData doInBackground(Void... params) { try { return RemoteConnector.createAnonymousUser(Constants.getAuthUrl(AuthenticatorActivity.this), new DeviceUuidFactory(AuthenticatorActivity.this).getDeviceUuid().toString()); } catch (NameNotFoundException e) { Log.e(Authenticator.class.getName(), "Failed to create anonymous user: " + e.getMessage()); return null; } } }.execute(); } else { super.setUp(); } }