List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:$.GooglePlayServicesExtension.java
public void onGSStringSave(String data, String desc, Integer id) { final String _data = data; final String _desc = desc; final Integer _id = id; Log.i("yoyo", "Google onGSStringSave called"); AsyncTask<Void, Void, Integer> task = new AsyncTask<Void, Void, Integer>() { @Override/*from w w w .java2s .c om*/ protected Integer doInBackground(Void... params) { boolean createIfMissing = true; byte[] databytes = _data.getBytes(); // Open the snapshot, creating if necessary Snapshots.OpenSnapshotResult open = Games.Snapshots .open(mGoogleApiClient, mCurrentSaveName, createIfMissing).await(); if (!open.getStatus().isSuccess()) { Log.i("yoyo", "Could not open Snapshot for saving."); return -1; } // Write the new data to the snapshot Snapshot snapshot = open.getSnapshot(); snapshot.getSnapshotContents().writeBytes(databytes); String s = new String(databytes); Log.i("yoyo", "saving snapshot:" + s); // Change metadata SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() .fromMetadata(snapshot.getMetadata()) .setDescription("Modified data at: " + Calendar.getInstance().getTime()) // .setCoverImage(bitmap) // .setDescription(description) // .setPlayedTimeMillis(playedTimeMillis) .build(); Snapshots.CommitSnapshotResult commit = Games.Snapshots .commitAndClose(mGoogleApiClient, snapshot, metadataChange).await(); if (!commit.getStatus().isSuccess()) { Log.i("yoyo", "Failed to commit Snapshot."); return -1; } Log.i("yoyo", "Commit Snapshot success"); return 0; } @Override protected void onPostExecute(Integer status) { // Dismiss progress dialog and reflect the changes in the UI. // ... Log.i("yoyo", "onGSStringSaves completed with " + status); } }; task.execute(); }
From source file:com.pk.wallpapermanager.PkWallpaperManager.java
/** * Sets the system wallpaper to the Wallpaper object passed. * <p>/* w w w .j av a 2 s. c om*/ * This does not guarantee success. For further detail, set a * listener * * @param mWall */ public void setWallpaperAsync(final Wallpaper mWall) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { setWallpaper(mWall); } catch (Exception e) { // Loop through all listeners notifying them for (WallpaperSetListener mListener : mWallpaperSetListeners) { mListener.onWallpaperSetFailed(); } e.printStackTrace(); } return null; } }.execute(); }
From source file:com.piusvelte.sonet.SonetCreatePost.java
@Override public void onClick(View v) { if (v == mSend) { if (!mAccountsService.isEmpty()) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() { @Override/* w w w. ja v a 2 s. c o m*/ protected Void doInBackground(Void... arg0) { Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator(); while (entrySet.hasNext()) { Map.Entry<Long, Integer> entry = entrySet.next(); final long accountId = entry.getKey(); final int service = entry.getValue(); final String placeId = mAccountsLocation.get(accountId); // post or comment! Cursor account = getContentResolver().query( Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { final String serviceName = Sonet.getServiceName(getResources(), service); publishProgress(serviceName); String message; SonetOAuth sonetOAuth; HttpPost httpPost; String response = null; switch (service) { case TWITTER: sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); // limit tweets to 140, breaking up the message if necessary 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); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); if (placeId != null) { params.add(new BasicNameValuePair("place_id", placeId)); params.add(new BasicNameValuePair("lat", mLat)); params.add(new BasicNameValuePair("long", mLong)); } try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case FACEBOOK: // handle tags StringBuilder tags = null; if (mAccountsTags.containsKey(accountId)) { String[] accountTags = mAccountsTags.get(accountId); if ((accountTags != null) && (accountTags.length > 0)) { tags = new StringBuilder(); tags.append("["); String tag_format; if (mPhotoPath != null) tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}"; else tag_format = "%s"; for (int i = 0, l = accountTags.length; i < l; i++) { if (i > 0) tags.append(","); tags.append(String.format(tag_format, accountTags[i])); } tags.append("]"); } } if (mPhotoPath != null) { // upload photo // uploading a photo takes a long time, have the service handle it Intent i = Sonet.getPackageIntent( SonetCreatePost.this.getApplicationContext(), PhotoUploadService.class); i.setAction(Sonet.ACTION_UPLOAD); i.putExtra(Accounts.TOKEN, account.getString(account.getColumnIndex(Accounts.TOKEN))); i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath); i.putExtra(Statuses.MESSAGE, mMessage.getText().toString()); i.putExtra(Splace, placeId); if (tags != null) i.putExtra(Stags, tags.toString()); startService(i); publishProgress(serviceName + " photo"); } else { // regular post httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL, Saccess_token, mSonetCrypto.Decrypt(account .getString(account.getColumnIndex(Accounts.TOKEN))))); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); if (placeId != null) params.add(new BasicNameValuePair(Splace, placeId)); if (tags != null) params.add(new BasicNameValuePair(Stags, tags.toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case MYSPACE: sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); try { HttpPut httpPut = new HttpPut( String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL)); httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY, mMessage.getText().toString()))); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPut)); } catch (IOException e) { Log.e(TAG, e.toString()); } // warn users about myspace permissions if (response != null) { publishProgress(serviceName, getString(R.string.success)); } else { publishProgress(serviceName, getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message)); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); if (placeId != null) { if (message != null) { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN, FOURSQUARE_BASE_URL, placeId, message, mLat, mLong, mSonetCrypto.Decrypt(account.getString( account.getColumnIndex(Accounts.TOKEN))))); } else { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT, FOURSQUARE_BASE_URL, placeId, mLat, mLong, mSonetCrypto.Decrypt(account.getString( account.getColumnIndex(Accounts.TOKEN))))); } } else { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE, FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account .getString(account.getColumnIndex(Accounts.TOKEN))))); } response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; case LINKEDIN: sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); try { httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL)); httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_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()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; case IDENTICA: sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); // limit tweets to 140, breaking up the message if necessary 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); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); if (placeId != null) { params.add(new BasicNameValuePair("place_id", placeId)); params.add(new BasicNameValuePair("lat", mLat)); params.add(new BasicNameValuePair("long", mLong)); } try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case CHATTER: // need to get an updated access_token response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(String.format( CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN)))))); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("instance_url") && jobj.has(Saccess_token)) { httpPost = new HttpPost(String.format(CHATTER_URL_POST, jobj.getString("instance_url"), Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + jobj.getString(Saccess_token)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } } catch (JSONException e) { Log.e(TAG, serviceName + ":" + e.toString()); Log.e(TAG, response); } } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; } } account.close(); } return null; } @Override protected void onProgressUpdate(String... params) { if (params.length == 1) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } else { (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG)) .show(); } } @Override protected void onPostExecute(Void result) { 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(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show(); } }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
@Override public void onClick(View v) { if (v == mSend) { if (!mAccountsService.isEmpty()) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() { @Override// ww w .j a v a2 s. co m protected Void doInBackground(Void... arg0) { Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator(); while (entrySet.hasNext()) { Map.Entry<Long, Integer> entry = entrySet.next(); final long accountId = entry.getKey(); final int service = entry.getValue(); final String placeId = mAccountsLocation.get(accountId); // post or comment! Cursor account = getContentResolver().query( Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { final String serviceName = Sonet.getServiceName(getResources(), service); publishProgress(serviceName); String message; SonetOAuth sonetOAuth; HttpPost httpPost; String response = null; switch (service) { case TWITTER: sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); // limit tweets to 140, breaking up the message if necessary 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); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); if (placeId != null) { params.add(new BasicNameValuePair("place_id", placeId)); params.add(new BasicNameValuePair("lat", mLat)); params.add(new BasicNameValuePair("long", mLong)); } try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case FACEBOOK: // handle tags StringBuilder tags = null; if (mAccountsTags.containsKey(accountId)) { String[] accountTags = mAccountsTags.get(accountId); if ((accountTags != null) && (accountTags.length > 0)) { tags = new StringBuilder(); tags.append("["); String tag_format; if (mPhotoPath != null) tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}"; else tag_format = "%s"; for (int i = 0, l = accountTags.length; i < l; i++) { if (i > 0) tags.append(","); tags.append(String.format(tag_format, accountTags[i])); } tags.append("]"); } } if (mPhotoPath != null) { // upload photo // uploading a photo takes a long time, have the service handle it Intent i = Sonet.getPackageIntent( SonetCreatePost.this.getApplicationContext(), PhotoUploadService.class); i.setAction(Sonet.ACTION_UPLOAD); i.putExtra(Accounts.TOKEN, account.getString(account.getColumnIndex(Accounts.TOKEN))); i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath); i.putExtra(Statuses.MESSAGE, mMessage.getText().toString()); i.putExtra(Splace, placeId); if (tags != null) i.putExtra(Stags, tags.toString()); startService(i); publishProgress(serviceName + " photo"); } else { // regular post httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL, Saccess_token, mSonetCrypto.Decrypt(account .getString(account.getColumnIndex(Accounts.TOKEN))))); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); if (placeId != null) params.add(new BasicNameValuePair(Splace, placeId)); if (tags != null) params.add(new BasicNameValuePair(Stags, tags.toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case MYSPACE: sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); try { HttpPut httpPut = new HttpPut( String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL)); httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY, mMessage.getText().toString()))); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPut)); } catch (IOException e) { Log.e(TAG, e.toString()); } // warn users about myspace permissions if (response != null) { publishProgress(serviceName, getString(R.string.success)); } else { publishProgress(serviceName, getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message)); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); if (placeId != null) { if (message != null) { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN, FOURSQUARE_BASE_URL, placeId, message, mLat, mLong, mSonetCrypto.Decrypt(account.getString( account.getColumnIndex(Accounts.TOKEN))))); } else { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT, FOURSQUARE_BASE_URL, placeId, mLat, mLong, mSonetCrypto.Decrypt(account.getString( account.getColumnIndex(Accounts.TOKEN))))); } } else { httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE, FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account .getString(account.getColumnIndex(Accounts.TOKEN))))); } response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; case LINKEDIN: sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); try { httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL)); httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_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()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; case IDENTICA: sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.SECRET)))); // limit tweets to 140, breaking up the message if necessary 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); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); if (placeId != null) { params.add(new BasicNameValuePair("place_id", placeId)); params.add(new BasicNameValuePair("lat", mLat)); params.add(new BasicNameValuePair("long", mLong)); } try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); } break; case CHATTER: // need to get an updated access_token response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost( String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mSonetCrypto.Decrypt( account.getString(account.getColumnIndex(Accounts.TOKEN)))))); if (response != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("instance_url") && jobj.has(Saccess_token)) { httpPost = new HttpPost(String.format(CHATTER_URL_POST, jobj.getString("instance_url"), Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + jobj.getString(Saccess_token)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } } catch (JSONException e) { Log.e(TAG, serviceName + ":" + e.toString()); Log.e(TAG, response); } } publishProgress(serviceName, getString(response != null ? R.string.success : R.string.failure)); break; } } account.close(); } return null; } @Override protected void onProgressUpdate(String... params) { if (params.length == 1) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } else { (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG)) .show(); } } @Override protected void onPostExecute(Void result) { 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(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show(); } }
From source file:com.shafiq.myfeedle.core.MyfeedleComments.java
@Override protected void onListItemClick(ListView list, View view, final int position, long id) { super.onListItemClick(list, view, position, id); final String sid = mComments.get(position).get(Statuses.SID); final String liked = mComments.get(position).get(getString(R.string.like)); // wait for previous attempts to finish if ((liked.length() > 0) && !liked.equals(getString(R.string.loading))) { // parse comment body, as in StatusDialog.java Matcher m = Myfeedle.getLinksMatcher(mComments.get(position).get(Statuses.MESSAGE)); int count = 0; while (m.find()) { count++;//from ww w . j a va2s . c om } // like comments, the first comment is the post itself switch (mService) { case TWITTER: // retweet items = new String[count + 1]; items[0] = getString(R.string.retweet); count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... arg0) { MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); HttpPost httpPost = new HttpPost( String.format(TWITTER_RETWEET, TWITTER_BASE_URL, sid)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); return MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } @Override protected void onPostExecute(String response) { setCommentStatus(0, getString(R.string.retweet)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString( response != null ? R.string.success : R.string.failure), Toast.LENGTH_LONG)).show(); } }; setCommentStatus(0, getString(R.string.loading)); asyncTask.execute(); } else { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); break; case FACEBOOK: items = new String[count + 1]; items[0] = getString( mComments.get(position).get(getString(R.string.like)) == getString(R.string.like) ? R.string.like : R.string.unlike); count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... arg0) { if (liked.equals(getString(R.string.like))) { return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpPost(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, sid, Saccess_token, mToken))); } else { HttpDelete httpDelete = new HttpDelete(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, sid, Saccess_token, mToken)); httpDelete.setHeader("Content-Length", "0"); return MyfeedleHttpClient.httpResponse(mHttpClient, httpDelete); } } @Override protected void onPostExecute(String response) { if (response != null) { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.unlike : R.string.like)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.success), Toast.LENGTH_LONG)).show(); } else { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.like : R.string.unlike)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; setCommentStatus(position, getString(R.string.loading)); asyncTask.execute(); } else { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); break; case LINKEDIN: if (position == 0) { items = new String[count + 1]; items[0] = getString( mComments.get(position).get(getString(R.string.like)) == getString(R.string.like) ? R.string.like : R.string.unlike); count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... arg0) { MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); HttpPut httpPut = new HttpPut( String.format(LINKEDIN_IS_LIKED, LINKEDIN_BASE_URL, mSid)); httpPut.addHeader( new BasicHeader("Content-Type", "application/xml")); try { httpPut.setEntity(new StringEntity( String.format(LINKEDIN_LIKE_BODY, Boolean.toString( liked.equals(getString(R.string.like)))))); return MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPut)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } return null; } @Override protected void onPostExecute(String response) { if (response != null) { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.unlike : R.string.like)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.success), Toast.LENGTH_LONG)).show(); } else { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.like : R.string.unlike)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; setCommentStatus(position, getString(R.string.loading)); asyncTask.execute(); } else { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW) .setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); } else { // no like option here items = new String[count]; count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if ((which < items.length) && (items[which] != null)) // open link startActivity( new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); } break; case IDENTICA: // retweet items = new String[count + 1]; items[0] = getString(R.string.repeat); count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... arg0) { MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); HttpPost httpPost = new HttpPost( String.format(IDENTICA_RETWEET, IDENTICA_BASE_URL, sid)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); return MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } @Override protected void onPostExecute(String response) { setCommentStatus(0, getString(R.string.repeat)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString( response != null ? R.string.success : R.string.failure), Toast.LENGTH_LONG)).show(); } }; setCommentStatus(0, getString(R.string.loading)); asyncTask.execute(); } else { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); break; case GOOGLEPLUS: //TODO: // plus1 items = new String[count]; count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); break; case CHATTER: if (position == 0) { items = new String[count + 1]; items[0] = getString( mComments.get(position).get(getString(R.string.like)) == getString(R.string.like) ? R.string.like : R.string.unlike); count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... arg0) { HttpUriRequest httpRequest; if (liked.equals(getString(R.string.like))) { httpRequest = new HttpPost(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid)); } else { httpRequest = new HttpDelete(String.format(CHATTER_URL_LIKE, mChatterInstance, mChatterLikeId)); } httpRequest.setHeader("Authorization", "OAuth " + mChatterToken); return MyfeedleHttpClient.httpResponse(mHttpClient, httpRequest); } @Override protected void onPostExecute(String response) { if (response != null) { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.unlike : R.string.like)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.success), Toast.LENGTH_LONG)).show(); } else { setCommentStatus(position, getString(liked.equals(getString(R.string.like)) ? R.string.like : R.string.unlike)); (Toast.makeText(MyfeedleComments.this, mServiceName + " " + getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; setCommentStatus(position, getString(R.string.loading)); asyncTask.execute(); } else { if ((which < items.length) && (items[which] != null)) // open link startActivity(new Intent(Intent.ACTION_VIEW) .setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); } else { // no like option here items = new String[count]; count = 1; m.reset(); while (m.find()) { items[count++] = m.group(); } mDialog = (new AlertDialog.Builder(this)) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if ((which < items.length) && (items[which] != null)) // open link startActivity( new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which]))); else (Toast.makeText(MyfeedleComments.this, getString(R.string.error_status), Toast.LENGTH_LONG)).show(); } }).setCancelable(true).setOnCancelListener(this).create(); mDialog.show(); } break; } } }
From source file:net.bytten.comicviewer.ComicViewerActivity.java
public void explain() { final IComicInfo comic = comicInfo; new AsyncTask<Object, Integer, Integer>() { @Override/*w w w . j a va 2s .c o m*/ protected Integer doInBackground(Object... params) { try { URL url = new URL(provider.getExplainUrl(comic).toString()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); return http.getResponseCode(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (result == null || result != 200) { toast("This comic has no user-supplied explanation."); } } }.execute(new Object[] {}); Intent browser = new Intent(); browser.setAction(Intent.ACTION_VIEW); browser.addCategory(Intent.CATEGORY_BROWSABLE); browser.setData(provider.getExplainUrl(comic)); startActivity(browser); }
From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java
/** * Import data previously exported./*from w w w.j ava 2 s . co m*/ * * @param context * {@link Context} * @param uri * {@link Uri} */ private void importData(final Context context, final Uri uri) { Log.d(TAG, "importData(ctx, " + uri + ")"); final ProgressDialog d1 = new ProgressDialog(this); d1.setCancelable(true); d1.setMessage(this.getString(R.string.import_progr)); d1.setIndeterminate(true); d1.show(); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(final Void... params) { StringBuilder sb = new StringBuilder(); try { final BufferedReader bufferedReader = // . new BufferedReader(new InputStreamReader(// . Preferences.this.getStream(Preferences.this.getContentResolver(), uri)), BUFSIZE); String line = bufferedReader.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = bufferedReader.readLine(); } } catch (Exception e) { Log.e(TAG, "error in reading export: " + e.toString(), e); return null; } return sb.toString(); } @Override protected void onPostExecute(final String result) { Log.d(TAG, "import:\n" + result); d1.dismiss(); if (result == null || result.length() == 0) { Toast.makeText(Preferences.this, R.string.err_export_read, Toast.LENGTH_LONG).show(); return; } String[] lines = result.split("\n"); if (lines.length <= 2) { Toast.makeText(Preferences.this, R.string.err_export_read, Toast.LENGTH_LONG).show(); return; } Builder builder = new Builder(Preferences.this); builder.setCancelable(true); builder.setTitle(R.string.import_rules_); builder.setMessage(Preferences.this.getString(R.string.import_rules_hint) + "\n" + URLDecoder.decode(lines[1])); 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) { d1.setCancelable(false); d1.setIndeterminate(true); d1.show(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(final Void... params) { DataProvider.importData(Preferences.this, result); return null; } @Override protected void onPostExecute(final Void result) { de.ub0r.android.callmeter.ui.Plans.reloadList(); d1.dismiss(); } } // . .execute((Void) null); } }); builder.show(); } } // . .execute((Void) null); }
From source file:com.pk.wallpapermanager.PkWallpaperManager.java
/** * Initializes our local wallpapers thread. *//*from w w w . j a v a2 s. com*/ private void initLocalWallpapersTask() { this.localWallpapersTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { fetchLocalWallpapers(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void p) { initLocalWallpapersTask(); } }; }
From source file:com.pk.wallpapermanager.PkWallpaperManager.java
/** * Initializes our cloud wallpapers thread. *///from w w w . ja v a 2 s . co m private void initCloudWallpapersTask() { this.cloudWallpapersTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { fetchCloudWallpapers(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void p) { initCloudWallpapersTask(); } }; }
From source file:android_network.hetnet.vpn_service.Util.java
public static void sendLogcat(final Uri uri, final Context context) { AsyncTask task = new AsyncTask<Object, Object, Intent>() { @Override/*from ww w .j av a2 s. c o m*/ protected Intent doInBackground(Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(context.getString(R.string.msg_issue)); sb.append("\r\n\r\n\r\n\r\n"); // Get version info String version = getSelfVersionName(context); sb.append(String.format("NetGuard: %s/%d\r\n", version, getSelfVersionCode(context))); sb.append(String.format("Android: %s (SDK %d)\r\n", Build.VERSION.RELEASE, Build.VERSION.SDK_INT)); sb.append("\r\n"); // Get device info sb.append(String.format("Brand: %s\r\n", Build.BRAND)); sb.append(String.format("Manufacturer: %s\r\n", Build.MANUFACTURER)); sb.append(String.format("Model: %s\r\n", Build.MODEL)); sb.append(String.format("Product: %s\r\n", Build.PRODUCT)); sb.append(String.format("Device: %s\r\n", Build.DEVICE)); sb.append(String.format("Host: %s\r\n", Build.HOST)); sb.append(String.format("Display: %s\r\n", Build.DISPLAY)); sb.append(String.format("Id: %s\r\n", Build.ID)); sb.append(String.format("Fingerprint: %B\r\n", hasValidFingerprint(context))); String abi; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) abi = Build.CPU_ABI; else abi = (Build.SUPPORTED_ABIS.length > 0 ? Build.SUPPORTED_ABIS[0] : "?"); sb.append(String.format("ABI: %s\r\n", abi)); sb.append("\r\n"); sb.append(String.format("VPN dialogs: %B\r\n", isPackageInstalled("com.android.vpndialogs", context))); try { sb.append(String.format("Prepared: %B\r\n", VpnService.prepare(context) == null)); } catch (Throwable ex) { sb.append("Prepared: ").append((ex.toString())).append("\r\n") .append(Log.getStackTraceString(ex)); } sb.append(String.format("Permission: %B\r\n", hasPhoneStatePermission(context))); sb.append("\r\n"); sb.append(getGeneralInfo(context)); sb.append("\r\n\r\n"); sb.append(getNetworkInfo(context)); sb.append("\r\n\r\n"); sb.append(getSubscriptionInfo(context)); sb.append("\r\n\r\n"); // Get settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Map<String, ?> all = prefs.getAll(); for (String key : all.keySet()) sb.append("Setting: ").append(key).append('=').append(all.get(key)).append("\r\n"); sb.append("\r\n"); // Write logcat OutputStream out = null; try { Log.i(TAG, "Writing logcat URI=" + uri); out = context.getContentResolver().openOutputStream(uri); out.write(getLogcat().toString().getBytes()); out.write(getTrafficLog(context).toString().getBytes()); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); sb.append(ex.toString()).append("\r\n").append(Log.getStackTraceString(ex)).append("\r\n"); } finally { if (out != null) try { out.close(); } catch (IOException ignored) { } } // Build intent Intent sendEmail = new Intent(Intent.ACTION_SEND); sendEmail.setType("message/rfc822"); sendEmail.putExtra(Intent.EXTRA_EMAIL, new String[] { "marcel+netguard@faircode.eu" }); sendEmail.putExtra(Intent.EXTRA_SUBJECT, "NetGuard " + version + " logcat"); sendEmail.putExtra(Intent.EXTRA_TEXT, sb.toString()); sendEmail.putExtra(Intent.EXTRA_STREAM, uri); return sendEmail; } @Override protected void onPostExecute(Intent sendEmail) { if (sendEmail != null) try { context.startActivity(sendEmail); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } }; task.execute(); }