List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.guster.brandon.library.webservice.RequestHandler.java
/** * Send Request to the server/* w w w .ja v a2s . c o m*/ */ public void send() { // Initializing parameters HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); httpClient = new DefaultHttpClient(httpParams); // check if there is any http authentication if (httpAuthenticator != null) { request.setHeader("Authorization", httpAuthenticator.getPasswordAuthentication()); } // add the user defined http headers accordingly for (HttpHeader h : headers) { request.addHeader(h.getName(), h.getValue()); } // send the request to server listener.onPrepare(this); new AsyncTask<Void, Void, Response>() { @Override protected Response doInBackground(Void... voids) { Response response = null; try { response = send(request); listener.onReceiveInBackground(response, (response != null && response.success())); //listener.onReceive(response); } catch (IOException e) { e.printStackTrace(); } return response; } @Override protected void onPostExecute(Response response) { listener.onReceive(response, (response != null && response.success())); /*if(response != null && response.success()) { listener.onSuccess(response); } else { listener.onFailed(response); }*/ } }.executeOnExecutor(asyncTaskExecutor); }
From source file:ca.rmen.android.poetassistant.main.dictionaries.search.Search.java
/** * Lookup a random word. Update the view pager tabs with the results of this word. *///w w w . j a v a2 s . c o m public void lookupRandom() { Log.d(TAG, "lookupRandom"); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { DictionaryEntry entry = mDictionary.getRandomEntry(); return entry == null ? null : entry.word; } @Override protected void onPostExecute(@Nullable String word) { if (word != null) { search(word); mViewPager.setCurrentItem(mPagerAdapter.getPositionForTab(Tab.DICTIONARY)); } } }.execute(); }
From source file:com.triarc.sync.SyncAdapter.java
private void sendLogs() { final LogCollector mLogCollector = new LogCollector(SyncAdapter.this.getContext()); new AsyncTask<Void, Void, Boolean>() { @Override/*from w ww . j a v a 2 s. com*/ protected Boolean doInBackground(Void... params) { try { mLogCollector.collect(); String path = SyncUtils.GetWebApiPath(SyncAdapter.this.getContext()); if (path == null) return true; mLogCollector.sendLog(path); } catch (Exception e) { e.printStackTrace(); } return true; } @Override protected void onPreExecute() { // showDialog(DIALOG_PROGRESS_COLLECTING_LOG); } @Override protected void onPostExecute(Boolean result) { } }.execute(); }
From source file:ca.ualberta.cmput301.t03.trading.TradeOfferHistoryFragment.java
@Override public void onRefresh() { AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override/* w w w . java 2s. co m*/ protected Void doInBackground(Void... params) { try { PrimaryUser.getInstance().refresh(); model = PrimaryUser.getInstance().getTradeList(); } catch (IOException e) { e.printStackTrace(); } catch (ServiceNotAvailableException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { if (adapter != null && model != null) { adapter.notifyUpdated(model); } if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setRefreshing(false); } } }; task.execute(); }
From source file:com.herokuapp.pushdemoandroid.DemoActivity.java
/** * Registers the application with GCM servers asynchronously. * <p>//from w ww. j a v a2 s . co m * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(CommonUtilities.SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. CommonUtilities.storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); }
From source file:com.burntout.burntout.DemoActivity.java
public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override// w w w .j a va2 s .c om protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); //data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; Log.d("regid", regid); Log.d("regid length", Integer.toString(regid.length())); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); sendRegistrationIdToBackend(); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } }
From source file:ch.christofbuechi.testgcm.MainActivity.java
public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override/*from ww w. j av a2s. 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.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); Log.i(this.getClass().getName(), "Button pressed"); msg = "Sent message"; sendRegistrationIdToBackend(); } 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.endiansoftware.echo.remotewatch.MainActivity.java
/** * Registers the application with GCM servers asynchronously. * <p>/*from w w w .j av a 2s . co m*/ * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { new HTTPGetRequestTask().execute("http://54.64.213.182:3000?regid=" + msg); } }.execute(null, null, null); }
From source file:com.ibm.mf.geofence.MFGeofencingManager.java
/** * Connect the Google API client. The synchronous / asynchronous mode depends on the {@link #mMode} of this geofence manager. *///from w w w.j av a2 s.c o m private void connectGoogleAPI() { if ((mContext != null) && (mMode != MODE_GEOFENCE_EVENT)) { mGoogleAPICallback = new GoogleLocationAPICallback(this); mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API) .addConnectionCallbacks(mGoogleAPICallback).addOnConnectionFailedListener(mGoogleAPICallback) .build(); log.debug("initGms() connecting to google play services ..."); if ((mMode == MODE_MONITORING_REQUEST) || (mMode == MODE_REBOOT)) { try { // can't run blockingConnect() on the UI thread ConnectionResult result = new AsyncTask<Void, Void, ConnectionResult>() { @Override protected ConnectionResult doInBackground(Void... params) { return mGoogleApiClient.blockingConnect(60_000L, TimeUnit.MILLISECONDS); } }.execute().get(); log.debug(String.format("google api connection %s, result=%s", (result.isSuccess() ? "success" : "error"), result)); } catch (Exception e) { log.error("error while attempting connection to google api", e); } } else if (mMode == MODE_APP) { mGoogleApiClient.connect(); } } }
From source file:com.piusvelte.sonet.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 av a 2 s .co 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(BuildConfig.TWITTER_KEY, BuildConfig.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(BuildConfig.MYSPACE_KEY, BuildConfig.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(BuildConfig.LINKEDIN_KEY, BuildConfig.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(BuildConfig.IDENTICA_KEY, BuildConfig.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); } } }