List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:net.majorkernelpanic.spydroid.ClientActivity.java
/** Fetch the current streaming configuration of the remote phone **/ private void getCurrentConfiguration() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); HttpConnectionParams.setSoTimeout(httpParameters, 3000); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet( "http://" + editTextIP.getText().toString() + ":8080/config.json?get"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = ""; try { response = client.execute(request, responseHandler); } catch (ConnectTimeoutException e) { Log.i(TAG, "Connection timeout ! "); onCompletion(null);/*from w ww . j a va 2 s . com*/ } catch (Exception e) { Log.e(TAG, "Could not fetch current configuration on remote device !"); e.printStackTrace(); } return response; } @Override protected void onPostExecute(String response) { try { JSONObject object = (JSONObject) new JSONTokener(response).nextValue(); ((CheckBox) findViewById(R.id.checkbox1)).setChecked(object.getBoolean("streamVideo")); ((CheckBox) findViewById(R.id.checkbox2)).setChecked(object.getBoolean("streamAudio")); for (int spinner : new int[] { R.id.spinner1, R.id.spinner2, R.id.spinner3, R.id.spinner4, R.id.spinner5 }) { Spinner view = (Spinner) findViewById(spinner); SpinnerAdapter adapter = view.getAdapter(); for (int i = 0; i < adapter.getCount(); i++) { Iterator<String> keys = object.keys(); while (keys.hasNext()) { String key = keys.next(); if (adapter.getItem(i).equals(object.get(key))) { view.setSelection(i); } } } } generateURI(); connectToServer(); } catch (Exception e) { stopStreaming(); e.printStackTrace(); } } }.execute(); }
From source file:com.perm.DoomPlay.VkAlbumsActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.itemNewAlbum) { AddListDialog dialog = new AddListDialog() { @Override/*w w w . j a v a 2 s . c o m*/ boolean isPlaylistExist(String playlist) { for (AudioAlbum album : albums) { if (album.title.equals(playlist)) return true; } return false; } @Override void createPlatlist(String playlist) { new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { try { handler.sendEmptyMessage(1); albums.add(0, new AudioAlbum(MainScreenActivity.api.addAudioAlbum(params[0]), params[0])); handler.sendEmptyMessage(2); } catch (IOException e) { showException(e); handler.sendEmptyMessage(2); cancel(true); } catch (JSONException e) { showException(e); handler.sendEmptyMessage(2); cancel(true); } catch (KException e) { handleKException(e); handler.sendEmptyMessage(2); cancel(true); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); adapter.notifyDataSetChanged(); } }.execute(playlist); } }; dialog.show(getSupportFragmentManager(), "tag"); return true; } return super.onOptionsItemSelected(item); }
From source file:com.github.gorbin.asne.googleplus.GooglePlusSocialNetwork.java
/** * Request {@link com.github.gorbin.asne.core.AccessToken} of Google plus social network that you can get from onRequestAccessTokenCompleteListener * @param onRequestAccessTokenCompleteListener listener for {@link com.github.gorbin.asne.core.AccessToken} request */// www . jav a 2 s .c o m @Override public void requestAccessToken(OnRequestAccessTokenCompleteListener onRequestAccessTokenCompleteListener) { super.requestAccessToken(onRequestAccessTokenCompleteListener); AsyncTask<Activity, Void, String> task = new AsyncTask<Activity, Void, String>() { @Override protected String doInBackground(Activity... params) { String scope = "oauth2:" + Scopes.PLUS_LOGIN; String token; String error = null; try { token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient), scope); try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); HttpConnectionParams.setSoTimeout(httpParameters, 20000); HttpClient client = new DefaultHttpClient(httpParameters); String url = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + token; HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(builder.toString()); JSONObject finalResult = new JSONObject(tokener); error = finalResult.getString("error"); } catch (Exception e) { //Probably shouldn't use Exception E here but there are quite a few //http/io/json exceptions that could occur } if (error != null && error.equals("invalid_token")) { GoogleAuthUtil.clearToken(params[0], token); token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient), scope); } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return token; } @Override protected void onPostExecute(String token) { if (token != null) { ((OnRequestAccessTokenCompleteListener) mLocalListeners.get(REQUEST_ACCESS_TOKEN)) .onRequestAccessTokenComplete(getID(), new AccessToken(token, null)); } else { mLocalListeners.get(REQUEST_ACCESS_TOKEN).onError(getID(), REQUEST_ACCESS_TOKEN, token, null); } } }; task.execute(mActivity); }
From source file:com.gridtelefon.DemoActivity.java
public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override/*from w ww . j ava 2s.c o m*/ protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.gridtelefon.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } }
From source file:com.chinaftw.music.model.MusicProvider.java
/** * Get the list of music tracks from a server and caches the track information * for future reference, keying tracks by musicId and grouping by genre. *//* w w w. jav a2 s . co m*/ public void retrieveMediaAsync(final Callback callback) { LogHelper.d(TAG, "retrieveMediaAsync called"); if (mCurrentState == State.INITIALIZED) { // Nothing to do, execute callback immediately callback.onMusicCatalogReady(true); return; } // Asynchronously load the music catalog in a separate thread new AsyncTask<Void, Void, State>() { @Override protected State doInBackground(Void... params) { retrieveMedia(); return mCurrentState; } @Override protected void onPostExecute(State current) { if (callback != null) { callback.onMusicCatalogReady(current == State.INITIALIZED); } } }.execute(); }
From source file:ti.modules.titanium.geolocation.TiLocation.java
private AsyncTask<Object, Void, Integer> getLookUpTask() { AsyncTask<Object, Void, Integer> task = new AsyncTask<Object, Void, Integer>() { @Override//w w w.jav a2 s . c o m protected Integer doInBackground(Object... args) { GeocodeResponseHandler geocodeResponseHandler = null; KrollDict event = null; try { String url = (String) args[0]; String direction = (String) args[1]; geocodeResponseHandler = (GeocodeResponseHandler) args[2]; Log.d(TAG, "GEO URL [" + url + "]", Log.DEBUG_MODE); HttpGet httpGet = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpClient client = new DefaultHttpClient(httpParams); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpGet, responseHandler); Log.i(TAG, "received Geo [" + response + "]", Log.DEBUG_MODE); if (response != null) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean(TiC.PROPERTY_SUCCESS)) { if (direction.equals("forward")) { event = buildForwardGeocodeResponse(jsonObject); } else { event = buildReverseGeocodeResponse(jsonObject); } event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); } else { event = new KrollDict(); String errorCode = "Unable to resolve message: Code (" + jsonObject.getString(TiC.ERROR_PROPERTY_ERRORCODE) + ")"; event.putCodeAndMessage(TiC.ERROR_CODE_UNKNOWN, errorCode); } } catch (JSONException e) { Log.e(TAG, "Error converting geo response to JSONObject [" + e.getMessage() + "]", e, Log.DEBUG_MODE); } } } catch (Throwable t) { Log.e(TAG, "Error retrieving geocode information [" + t.getMessage() + "]", t, Log.DEBUG_MODE); } if (geocodeResponseHandler != null) { if (event == null) { event = new KrollDict(); event.putCodeAndMessage(TiC.ERROR_CODE_UNKNOWN, "Error obtaining geolocation"); } geocodeResponseHandler.handleGeocodeResponse(event); } return -1; } }; return task; }
From source file:com.piusvelte.sonet.core.SonetComments.java
@Override public void onClick(View v) { if (v == mSend) { if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0) && (mSid != null) && (mEsid != null)) { mMessage.setEnabled(false);//from w w w . j a v a 2 s .c o m mSend.setEnabled(false); // post or comment! final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... arg0) { List<NameValuePair> params; String message; String response = null; HttpPost httpPost; SonetOAuth sonetOAuth; String serviceName = Sonet.getServiceName(getResources(), mService); publishProgress(serviceName); switch (mService) { case TWITTER: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case FACEBOOK: httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case MYSPACE: sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret); try { httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)); httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY, mMessage.getText().toString()))); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL, mSid, message, mToken)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case LINKEDIN: sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); try { httpPost = new HttpPost( String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); httpPost.setEntity(new StringEntity( String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString()))); httpPost.addHeader(new BasicHeader("Content-Type", "application/xml")); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case IDENTICA: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case GOOGLEPLUS: break; case CHATTER: httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid, Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + mChatterToken); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); break; } return ((response == null) && (mService == MYSPACE)) ? null : serviceName + " " + getString(response != null ? R.string.success : R.string.failure); } @Override protected void onProgressUpdate(String... params) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } @Override protected void onPostExecute(String result) { if (result != null) { (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show(); } else if (mService == MYSPACE) { // myspace permissions (Toast.makeText(SonetComments.this, SonetComments.this.getResources() .getStringArray(R.array.service_entries)[MYSPACE] + getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message), Toast.LENGTH_LONG)).show(); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); finish(); } }; 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(); } else { (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show(); mMessage.setEnabled(true); mSend.setEnabled(true); } } }
From source file:com.imobilize.blogposts.fragments.SubscribeFragment.java
private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override/*from w w w . j av a 2 s . c o m*/ protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(Constants.SENDER_ID); msg = "Device registered, registration ID=" + regid; sendRegistrationIdToBackend(); storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(context, "Registration Completed. Now you can see the notifications", Toast.LENGTH_SHORT).show(); Log.v(Constants.TAG, result); } }.execute(null, null, null); }
From source file:com.nokia.example.pepperfarm.iap.Payment.java
/** * Fetches the prices asynchronously//from ww w . j a v a 2 s .co m */ public void fetchPrices() { if (!isBillingAvailable()) return; for (Product p : Content.ITEMS) { if (p.getPrice() != "") { Log.i("fetchPrices", "Prices already available. Not fetching."); return; } } AsyncTask<Void, String, Void> pricesTask = new AsyncTask<Void, String, Void>() { @Override protected Void doInBackground(Void... params) { ArrayList<String> productIdArray = new ArrayList<String>(Content.ITEM_MAP.keySet()); Bundle productBundle = new Bundle(); productBundle.putStringArrayList("ITEM_ID_LIST", productIdArray); try { Bundle priceInfo = npay.getProductDetails(API_VERSION, activity.getPackageName(), ITEM_TYPE_INAPP, productBundle); if (priceInfo.getInt("RESPONSE_CODE", RESULT_ERR) == RESULT_OK) { ArrayList<String> productDetailsList = priceInfo.getStringArrayList("DETAILS_LIST"); for (String productDetails : productDetailsList) { parseProductDetails(productDetails); } } else { Log.e("fetchPrices", "PRICE - priceInfo was not ok: Result was: " + priceInfo.getInt("RESPONSE_CODE", -100)); } } catch (JSONException e) { Log.e("fetchPrices", "PRODUCT DETAILS PARSING EXCEPTION: " + e.getMessage(), e); } catch (RemoteException e) { Log.e("fetchPrices", "PRICE EXCEPTION: " + e.getMessage(), e); } return null; } private void parseProductDetails(String productDetails) throws JSONException { ProductDetails details = new ProductDetails(productDetails); Log.i("fetchPrices", productDetails); Product p = Content.ITEM_MAP.get(details.getProductId()); if (p != null) { p.setPrice(details.getPriceFormatted()); Log.i("fetchPrices", "PRICE RECEIVED - " + details.getPrice() + " " + details.getCurrency()); } else { Log.i("fetchPrices", "Unable to set price for product " + details.getProductId() + ". Product not found."); } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (ProductListFragment.purchaseListAdapter != null) { ProductListFragment.purchaseListAdapter.notifyDataSetChanged(); } if (MainScreenPepperListFragment.reference.adapter != null) { MainScreenPepperListFragment.reference.adapter.notifyDataSetChanged(); } } }; pricesTask.execute(); }
From source file:ca.ualberta.cmput301.t03.inventory.BrowseInventoryFragment.java
@Override public void onRefresh() { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override/*from w ww . j a va2s. c o m*/ protected Void doInBackground(Void... params) { try { PrimaryUser.getInstance().refresh(); model = PrimaryUser.getInstance().getBrowseableInventories(filters); //fixme browseableinventories actually needs to refresh } catch (IOException e) { throw new RuntimeException(e); } catch (ServiceNotAvailableException e) { throw new RuntimeException(e); } return null; } @Override protected void onPostExecute(Void aVoid) { // model.setFilters(filters); if (model.size() > 0) { if (init) { init = false; setupListView(); } else { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } adapter.notifyUpdated(model); } } else { synchronized (uiLock) { if (getActivity().getSupportFragmentManager() != null) { getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.fragmentContent, NoFriendsBrowseInventory.newInstance()).commit(); } } } } }; task.execute(); }