List of usage examples for android.os AsyncTask AsyncTask
public AsyncTask()
From source file:com.shafiq.myfeedle.core.MyfeedleNotifications.java
@Override public boolean onOptionsItemSelected(MenuItem item) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Integer, String, Boolean> asyncTask = new AsyncTask<Integer, String, Boolean>() { @Override/*www . j av a 2 s. c o m*/ protected Boolean doInBackground(Integer... arg0) { if (arg0[0] == R.id.menu_notifications_refresh) { // select all accounts with notifications set Cursor widgets = getContentResolver().query( Widgets_settings.getDistinctContentUri(MyfeedleNotifications.this), new String[] { Widgets.ACCOUNT }, Widgets.ACCOUNT + "!=-1 and (" + Widgets.LIGHTS + "=1 or " + Widgets.VIBRATE + "=1 or " + Widgets.SOUND + "=1)", null, null); if (widgets.moveToFirst()) { mMyfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext()); HttpClient httpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()); while (!widgets.isAfterLast()) { long accountId = widgets.getLong(0); ArrayList<String> notificationSids = new ArrayList<String>(); Cursor account = getContentResolver().query( Accounts.getContentUri(MyfeedleNotifications.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE, Accounts.SID }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { // for each account, for each notification, check for updates // if there are no updates past 24hrs and cleared, delete String token = mMyfeedleCrypto.Decrypt(account.getString(0)); String secret = mMyfeedleCrypto.Decrypt(account.getString(1)); int service = account.getInt(2); String accountEsid = mMyfeedleCrypto.Decrypt(account.getString(3)); mSimpleDateFormat = null; if (service == TWITTER) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); // loop over notifications if (currentNotifications.moveToFirst()) { // store sids, to avoid duplicates when requesting the latest feed String sid = mMyfeedleCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(MyfeedleNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mMyfeedleCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_MENTIONS, TWITTER_BASE_URL, last_sid != null ? String.format(TWITTER_SINCE_ID, last_sid) : "")))); if (response != null) { try { JSONArray comments = new JSONArray(response); for (int i = 0, i2 = comments.length(); i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); if (!user.getString(Sid).equals(accountEsid) && !notificationSids.contains(comment.getString(Sid))) { String friend = user.getString(Sname); addNotification(comment.getString(Sid), user.getString(Sid), friend, comment.getString("text"), parseDate(comment.getString("created_at"), TWITTER_DATE_FORMAT), accountId, friend + " mentioned you on Twitter"); } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } } else if (service == IDENTICA) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); // loop over notifications if (currentNotifications.moveToFirst()) { // store sids, to avoid duplicates when requesting the latest feed String sid = mMyfeedleCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(MyfeedleNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mMyfeedleCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(IDENTICA_MENTIONS, IDENTICA_BASE_URL, last_sid != null ? String.format(IDENTICA_SINCE_ID, last_sid) : "")))); if (response != null) { try { JSONArray comments = new JSONArray(response); for (int i = 0, i2 = comments.length(); i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); if (!user.getString(Sid).equals(accountEsid) && !notificationSids.contains(comment.getString(Sid))) { String friend = user.getString(Sname); addNotification(comment.getString(Sid), user.getString(Sid), friend, comment.getString("text"), parseDate(comment.getString("created_at"), TWITTER_DATE_FORMAT), accountId, friend + " mentioned you on Identi.ca"); } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } } else { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications._ID, Notifications.SID, Notifications.UPDATED, Notifications.CLEARED, Notifications.ESID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); if (currentNotifications.moveToFirst()) { String response; MyfeedleOAuth myfeedleOAuth; switch (service) { case FACEBOOK: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet( String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, sid, Saccess_token, token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONArray(Sdata); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(Screated_time) * 1000; if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject from = comment.getJSONObject(Sfrom); if (accountEsid.equals(from.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), from.getString(Sname))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), from.getString(Sname) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FACEBOOK_HOME, FACEBOOK_BASE_URL, Saccess_token, token)))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Sdata); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(Sid); // if already notified, ignore if (!notificationSids.contains(sid)) { // only parse status types, not photo, video or link if (o.has(Stype) && o.has(Sfrom)) { JSONObject f = o.getJSONObject(Sfrom); if (f.has(Sname) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(Sname); if (o.has(Sto)) { // handle wall messages from one friend to another JSONObject t = o.getJSONObject(Sto); if (t.has(Sdata)) { JSONObject n = t.getJSONArray(Sdata) .getJSONObject(0); if (n.has(Sname)) { if (n.has(Sid) && (n .getString(Sid) .equals(accountEsid))) { notification = String .format(getString( R.string.friendcommented), friend); } } } } int commentCount = 0; if (o.has(Scomments)) { JSONObject jo = o .getJSONObject(Scomments); if (jo.has(Sdata)) { JSONArray comments = jo .getJSONArray(Sdata); commentCount = comments.length(); // notifications if ((sid != null) && (commentCount > 0)) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals( accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sfrom)) { JSONObject c4 = c3 .getJSONObject( Sfrom); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( Sname)); } } } } } } if (notification != null) { String message = o.has(Smessage) ? o.getString(Smessage) : null; if (!o.getString(Stype).equals(Sstatus) && o.has(Slink)) { message = message == null ? "[" + o.getString(Stype) + "]" : "[" + o.getString(Stype) + "]"; } // new notification addNotification(sid, esid, friend, message, o.getLong(Screated_time) * 1000, accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case MYSPACE: myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; String esid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(4)); // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(new HttpGet( String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, esid, sid))))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONArray(Sentry); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = parseDate( comment.getString(SpostedDate), MYSPACE_DATE_FORMAT); if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject author = comment .getJSONObject(Sauthor); if (accountEsid.equals(author.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), comment.getString( SdisplayName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), comment.getString( SdisplayName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient .httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(MYSPACE_HISTORY, MYSPACE_BASE_URL))))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Sentry); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(SstatusId); // if already notified, ignore if (!notificationSids.contains(sid)) { if (o.has(Sauthor) && o.has(SrecentComments)) { JSONObject f = o.getJSONObject(Sauthor); if (f.has(SdisplayName) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(SdisplayName); JSONArray comments = o .getJSONArray(SrecentComments); int commentCount = comments.length(); // notifications if ((sid != null) && (commentCount > 0)) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sauthor)) { JSONObject c4 = c3 .getJSONObject(Sauthor); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SdisplayName)); } } } } if (notification != null) { // new notification addNotification(sid, esid, friend, o.getString(Sstatus), parseDate(o.getString( "moodStatusLastUpdated"), MYSPACE_DATE_FORMAT), accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case FOURSQUARE: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, sid, token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONObject(Sresponse).getJSONObject(Scheckin) .getJSONObject(Scomments).getJSONArray(Sitems); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(ScreatedAt) * 1000; if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject user = comment.getJSONObject(Suser); if (accountEsid.equals(user.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), user.getString(SfirstName) + " " + user.getString( SlastName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), user.getString(SfirstName) + " " + user.getString( SlastName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FOURSQUARE_CHECKINS, FOURSQUARE_BASE_URL, token)))) != null) { try { JSONArray jarr = new JSONObject(response) .getJSONObject(Sresponse).getJSONArray(Srecent); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(Sid); // if already notified, ignore if (!notificationSids.contains(sid)) { if (o.has(Suser) && o.has(Scomments)) { JSONObject f = o.getJSONObject(Suser); if (f.has(SfirstName) && f.has(SlastName) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(SfirstName) + " " + f.getString(SlastName); JSONArray comments = o .getJSONArray(Scomments); int commentCount = comments.length(); // notifications if (commentCount > 0) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Suser)) { JSONObject c4 = c3 .getJSONObject(Suser); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SfirstName) + " " + c4.getString( SlastName)); } } } } if (notification != null) { String message = ""; if (o.has(Sshout)) { message = o.getString(Sshout) + "\n"; } if (o.has(Svenue)) { JSONObject venue = o .getJSONObject(Svenue); if (venue.has(Sname)) { message += "@" + venue .getString(Sname); } } // new notification addNotification(sid, esid, friend, message, o.getLong(ScreatedAt) * 1000, accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case LINKEDIN: myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications HttpGet httpGet = new HttpGet(String .format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, sid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(httpGet))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) { JSONArray comments = jsonResponse.getJSONArray(Svalues); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(Stimestamp); if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject person = comment .getJSONObject(Sperson); if (accountEsid .equals(person.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), person.getString( SfirstName) + " " + person.getString( SlastName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), person.getString( SfirstName) + " " + person.getString( SlastName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long.toString( notificationId) }); } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed HttpGet httpGet = new HttpGet( String.format(LINKEDIN_UPDATES, LINKEDIN_BASE_URL)); for (String[] header : LINKEDIN_HEADERS) { httpGet.setHeader(header[0], header[1]); } if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(httpGet))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Svalues); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(SupdateKey); // if already notified, ignore if (!notificationSids.contains(sid)) { String updateType = o.getString(SupdateType); JSONObject updateContent = o .getJSONObject(SupdateContent); if (LinkedIn_UpdateTypes.contains(updateType) && updateContent.has(Sperson)) { JSONObject f = updateContent .getJSONObject(Sperson); if (f.has(SfirstName) && f.has(SlastName) && f.has(Sid) && o.has(SupdateComments)) { JSONObject updateComments = o .getJSONObject(SupdateComments); if (updateComments.has(Svalues)) { String notification = null; String esid = f.getString(Sid); JSONArray comments = updateComments .getJSONArray(Svalues); int commentCount = comments.length(); // notifications if (commentCount > 0) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sperson)) { JSONObject c4 = c3 .getJSONObject( Sperson); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SfirstName) + " " + c4.getString( SlastName)); } } } } if (notification != null) { String update = LinkedIn_UpdateTypes .getMessage(updateType); if (LinkedIn_UpdateTypes.APPS.name() .equals(updateType)) { if (f.has(SpersonActivities)) { JSONObject personActivities = f .getJSONObject( SpersonActivities); if (personActivities .has(Svalues)) { JSONArray updates = personActivities .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( Sbody); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.CONN .name() .equals(updateType)) { if (f.has(Sconnections)) { JSONObject connections = f .getJSONObject( Sconnections); if (connections .has(Svalues)) { JSONArray updates = connections .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( SfirstName) + " " + updates .getJSONObject( u) .getString( SlastName); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.JOBP .name() .equals(updateType)) { if (updateContent.has(Sjob) && updateContent .getJSONObject( Sjob) .has(Sposition) && updateContent .getJSONObject( Sjob) .getJSONObject( Sposition) .has(Stitle)) update += updateContent .getJSONObject(Sjob) .getJSONObject( Sposition) .getString(Stitle); } else if (LinkedIn_UpdateTypes.JGRP .name() .equals(updateType)) { if (f.has(SmemberGroups)) { JSONObject memberGroups = f .getJSONObject( SmemberGroups); if (memberGroups .has(Svalues)) { JSONArray updates = memberGroups .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( Sname); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.PREC .name() .equals(updateType)) { if (f.has( SrecommendationsGiven)) { JSONObject recommendationsGiven = f .getJSONObject( SrecommendationsGiven); if (recommendationsGiven .has(Svalues)) { JSONArray updates = recommendationsGiven .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { JSONObject recommendation = updates .getJSONObject( u); JSONObject recommendee = recommendation .getJSONObject( Srecommendee); if (recommendee.has( SfirstName)) update += recommendee .getString( SfirstName); if (recommendee.has( SlastName)) update += recommendee .getString( SlastName); if (recommendation .has(SrecommendationSnippet)) update += ":" + recommendation .getString( SrecommendationSnippet); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.SHAR .name().equals(updateType) && f.has(ScurrentShare)) { JSONObject currentShare = f .getJSONObject( ScurrentShare); if (currentShare.has(Scomment)) update = currentShare .getString( Scomment); } // new notification addNotification(sid, esid, f.getString(SfirstName) + " " + f.getString( SlastName), update, o.getLong(Stimestamp), accountId, notification); } } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case GOOGLEPLUS: // get new access token, need different request here HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> httpParams = new ArrayList<NameValuePair>(); httpParams.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID)); httpParams.add( new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET)); httpParams.add(new BasicNameValuePair("refresh_token", token)); httpParams.add(new BasicNameValuePair("grant_type", "refresh_token")); try { httpPost.setEntity(new UrlEncodedFormEntity(httpParams)); if ((response = MyfeedleHttpClient.httpResponse(httpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has(Saccess_token)) { String access_token = j.getString(Saccess_token); while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse( httpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL, sid, access_token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONObject item = new JSONObject(response); if (item.has(Sobject)) { JSONObject object = item .getJSONObject(Sobject); if (object.has(Sreplies)) { int commentCount = 0; JSONObject replies = object .getJSONObject(Sreplies); if (replies.has(StotalItems)) { //TODO: notifications } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // get new feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITIES, GOOGLEPLUS_BASE_URL, "me", "public", 20, access_token)))) != null) { JSONObject r = new JSONObject(response); if (r.has(Sitems)) { JSONArray items = r.getJSONArray(Sitems); for (int i1 = 0, i2 = items .length(); i1 < i2; i1++) { JSONObject item = items.getJSONObject(i1); if (item.has(Sactor) && item.has(Sobject)) { JSONObject actor = item .getJSONObject(Sactor); JSONObject object = item .getJSONObject(Sobject); if (item.has(Sid) && actor.has(Sid) && actor.has(SdisplayName) && item.has(Spublished) && object.has(Sreplies) && object.has(SoriginalContent)) { String sid = item.getString(Sid); String esid = actor.getString(Sid); String friend = actor .getString(SdisplayName); String originalContent = object .getString(SoriginalContent); if ((originalContent == null) || (originalContent .length() == 0)) { originalContent = object .getString(Scontent); } String photo = null; if (actor.has(Simage)) { JSONObject image = actor .getJSONObject(Simage); if (image.has(Surl)) { photo = image.getString(Surl); } } long date = parseDate( item.getString(Spublished), GOOGLEPLUS_DATE_FORMAT); int commentCount = 0; JSONObject replies = object .getJSONObject(Sreplies); String notification = null; if (replies.has(StotalItems)) { Log.d(TAG, Sreplies + ":" + replies.toString()); commentCount = replies .getInt(StotalItems); } if (notification != null) { // new notification addNotification(sid, esid, friend, originalContent, date, accountId, notification); } } } } } } } } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } currentNotifications.close(); } // remove old notifications getContentResolver().delete(Notifications.getContentUri(MyfeedleNotifications.this), Notifications.CLEARED + "=1 and " + Notifications.ACCOUNT + "=? and " + Notifications.CREATED + "<?", new String[] { Long.toString(accountId), Long.toString(System.currentTimeMillis() - 86400000) }); } account.close(); widgets.moveToNext(); } } else { publishProgress("No notifications have been set up on any accounts."); } widgets.close(); return false; } else if (arg0[0] == R.id.menu_notifications_clear_all) { // clear all notifications ContentValues values = new ContentValues(); values.put(Notifications.CLEARED, 1); MyfeedleNotifications.this.getContentResolver() .update(Notifications.getContentUri(MyfeedleNotifications.this), values, null, null); return true; } return false; } @Override protected void onProgressUpdate(String... messages) { (Toast.makeText(MyfeedleNotifications.this, messages[0], Toast.LENGTH_LONG)).show(); } @Override protected void onPostExecute(Boolean finish) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } if (finish) { MyfeedleNotifications.this.finish(); } } private void addNotification(String sid, String esid, String friend, String message, long created, long accountId, String notification) { ContentValues values = new ContentValues(); values.put(Notifications.SID, sid); values.put(Notifications.ESID, esid); values.put(Notifications.FRIEND, friend); values.put(Notifications.MESSAGE, message); values.put(Notifications.CREATED, created); values.put(Notifications.ACCOUNT, accountId); values.put(Notifications.NOTIFICATION, notification); values.put(Notifications.CLEARED, 0); values.put(Notifications.UPDATED, created); getContentResolver().insert(Notifications.getContentUri(MyfeedleNotifications.this), values); } private long parseDate(String date, String format) { if (date != null) { // hack for the literal 'Z' if (date.substring(date.length() - 1).equals("Z")) { date = date.substring(0, date.length() - 2) + "+0000"; } Date created = null; if (format != null) { if (mSimpleDateFormat == null) { mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH); // all dates should be GMT/UTC mSimpleDateFormat.setTimeZone(sTimeZone); } try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } else { // attempt to parse RSS date if (mSimpleDateFormat != null) { try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } for (String rfc822 : sRFC822) { mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH); mSimpleDateFormat.setTimeZone(sTimeZone); try { if ((created = mSimpleDateFormat.parse(date)) != null) { return created.getTime(); } } catch (ParseException e) { Log.e(TAG, e.toString()); } } } } return System.currentTimeMillis(); } }; 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(item.getItemId()); return true; // return super.onOptionsItemSelected(item); }
From source file:com.piusvelte.sonet.SonetCreatePost.java
private void setLocation(final long accountId) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { int serviceId; @Override//w w w . j av a2 s. c o m protected String doInBackground(Void... none) { Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { SonetOAuth sonetOAuth; serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE)); switch (serviceId) { case TWITTER: // anonymous requests are rate limited to 150 per hour // authenticated requests are rate limited to 350 per hour, so authenticate this! 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)))); return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong)))); case FACEBOOK: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong, Saccess_token, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); case FOURSQUARE: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format( FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); } } account.close(); return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { switch (serviceId) { case TWITTER: try { JSONArray places = new JSONObject(response).getJSONObject(Sresult) .getJSONArray(Splaces); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sfull_name); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FACEBOOK: try { JSONArray places = new JSONObject(response).getJSONArray(Sdata); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { JSONArray groups = new JSONObject(response).getJSONObject(Sresponse) .getJSONArray(Sgroups); for (int g = 0, g2 = groups.length(); g < g2; g++) { JSONObject group = groups.getJSONObject(g); if (group.getString(Sname).equals(SNearby)) { JSONArray places = group.getJSONArray(Sitems); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } else { (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; 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(); }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
private void setLocation(final long accountId) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { int serviceId; @Override//from w ww.j av a2 s .c om protected String doInBackground(Void... none) { Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { SonetOAuth sonetOAuth; serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE)); switch (serviceId) { case TWITTER: // anonymous requests are rate limited to 150 per hour // authenticated requests are rate limited to 350 per hour, so authenticate this! sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET)))); return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong)))); case FACEBOOK: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong, Saccess_token, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); case FOURSQUARE: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format( FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); } } account.close(); return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { switch (serviceId) { case TWITTER: try { JSONArray places = new JSONObject(response).getJSONObject(Sresult) .getJSONArray(Splaces); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sfull_name); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FACEBOOK: try { JSONArray places = new JSONObject(response).getJSONArray(Sdata); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { JSONArray groups = new JSONObject(response).getJSONObject(Sresponse) .getJSONArray(Sgroups); for (int g = 0, g2 = groups.length(); g < g2; g++) { JSONObject group = groups.getJSONObject(g); if (group.getString(Sname).equals(SNearby)) { JSONArray places = group.getJSONArray(Sitems); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } else { (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; 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(); }
From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java
private void runTests() { MobileServiceClient client = null;/*from w ww . j av a 2 s . co m*/ try { client = createMobileServiceClient(); } catch (MalformedURLException e) { createAndShowDialog(e, "Error"); } // getMobileServiceRuntimeFeatures(client); final TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem(); logWithTimestamp(new Date(), "Tests for group \'" + group.getName() + "\'"); logSeparator(); final MobileServiceClient currentClient = client; if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // For android versions 4.0.x // Run a first Void AsyncTask on UI thread to enable the possibility // of running others on sub threads new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { return null; } }.execute(); } Thread thread = new Thread() { @Override public void run() { group.runTests(currentClient, new TestExecutionCallback() { @Override public void onTestStart(TestCase test) { final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter(); runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); } }); log("TEST START", test.getName()); } @Override public void onTestGroupComplete(TestGroup group, List<TestResult> results) { log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString()); logSeparator(); if (group.getName().startsWith(TestGroup.AllTestsGroupName)) { List<TestCase> tests = new ArrayList<TestCase>(); for (TestResult result : results) { tests.add(result.getTestCase()); } DaylightLogger logger = new DaylightLogger(getDaylightURL(), getDaylightProject(), getDaylightClientId(), getDaylightClientSecret(), getDaylightRuntime(), getDaylightRunId()); try { logger.reportResultsToDaylight(group.getFailedTestCount(), group.getStartTime(), group.getEndTime(), tests, group.getSourceMap()); } catch (Throwable e) { log(e.getMessage()); } } if (shouldRunUnattended()) { // String logContent = mLog.toString(); // postLogs(logContent, true); boolean passed = true; for (TestResult result : results) { if (result.getStatus() != TestStatus.Passed) { passed = false; break; } } try { String sdCard = Environment.getExternalStorageDirectory().getPath(); FileOutputStream fos = new FileOutputStream(sdCard + "/done_android_e2e.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write("Completed successfully.\n"); bw.write(passed ? "PASSED" : "FAILED"); bw.write("\n"); bw.close(); osw.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onTestComplete(TestCase test, TestResult result) { Throwable e = result.getException(); if (e != null) { StringBuilder sb = new StringBuilder(); while (e != null) { sb.append(e.getClass().getSimpleName() + ": "); sb.append(e.getMessage()); sb.append("\n"); sb.append(Log.getStackTraceString(e)); sb.append("\n\n"); e = e.getCause(); } test.log("Exception: " + sb.toString()); } final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter(); runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); } }); logWithTimestamp(test.getStartTime(), "Logs for test " + test.getName() + " (" + result.getStatus().toString() + ")"); String testLogs = test.getLog(); if (testLogs.length() > 0) { if (testLogs.endsWith("\n")) { testLogs = testLogs.substring(0, testLogs.length() - 1); } log(testLogs); } logWithTimestamp(test.getEndTime(), "Test " + result.getStatus().toString()); logWithTimestamp(test.getEndTime(), "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-"); logSeparator(); } }); } }; thread.start(); }
From source file:com.almarsoft.GroundhogReader.MessageListActivity.java
private void catchupGroup() { AsyncTask<String, Void, Void> catchupTask = new AsyncTask<String, Void, Void>() { @Override//from w ww .j a v a 2 s . c o m protected Void doInBackground(String... groupArr) { try { mServerManager.catchupGroup(mGroup); } catch (IOException e) { Log.w("Groundhog", "Problem catching up with the server"); e.printStackTrace(); } catch (ServerAuthException e) { Log.w("Groundhog", "Problem catching up with the server"); e.printStackTrace(); } return null; } protected void onPostExecute(Void arg0) { Toast.makeText(MessageListActivity.this, R.string.catchup_done, Toast.LENGTH_SHORT); dismissDialog(ID_DIALOG_CATCHUP); } }; showDialog(ID_DIALOG_CATCHUP); catchupTask.execute(mGroup); }
From source file:au.org.intersect.faims.android.ui.activity.ShowModuleActivity.java
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_show_module); // inject faimsClient and serverDiscovery RoboGuice.getBaseApplicationInjector(this.getApplication()).injectMembers(this); // initialize server discovery serverDiscovery.setApplication(getApplication()); // Need to register license for the map view before create an instance of map view CustomMapView.registerLicense(getApplicationContext()); this.activityData = new ShowModuleActivityData(); rotation = AnimationUtils.loadAnimation(this, R.anim.clockwise); rotation.setRepeatCount(Animation.INFINITE); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); syncAnimImage = (ImageView) inflater.inflate(R.layout.rotate, null); setupSync();/*from w w w .j av a 2s . co m*/ setupWifiBroadcast(); setupModule(); setProgressBarIndeterminateVisibility(false); // set file browser to reset last location when activity is created DisplayPrefs.setLastLocation(ShowModuleActivity.this, getModuleDir()); busyDialog = new BusyDialog(this, getString(R.string.load_module_title), getString(R.string.load_module_message), null); busyDialog.show(); new AsyncTask<Void, Void, Void>() { @Override protected void onPostExecute(Void result) { renderUI(savedInstanceState); busyDialog.dismiss(); } @Override protected Void doInBackground(Void... params) { preRenderUI(); return null; }; }.execute(); }
From source file:com.df.push.DemoActivity.java
private void subscribe(final String topic, final String endPoint) { final String url = "https://next.cloud.dreamfactory.com/rest/sns/subscription?app_name=todoangular"; new AsyncTask<Void, Void, String>() { @Override//from w w w. ja v a 2 s. c o m protected String doInBackground(Void... params) { String msg = ""; JSONObject obj = new JSONObject(); try { obj.put("Topic", topic); obj.put("Protocol", "application"); obj.put("Endpoint", endPoint); } catch (JSONException e1) { e1.printStackTrace(); } HttpResponse<JsonNode> jsonResponse; try { jsonResponse = Unirest.post(url).header("accept", "application/json").body(obj.toString()) .asJson(); msg = "Subscribe response " + jsonResponse.getBody().toString(); subscriptions.add(jsonResponse.getBody().getObject().getString("SubscriptionArn")); Log.i(TAG, msg); } catch (Exception e) { msg = e.getLocalizedMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); progressDialog.dismiss(); } @Override protected void onPreExecute() { if (progressDialog != null) progressDialog.show(); }; }.execute(null, null, null); }
From source file:biz.bokhorst.xprivacy.ActivityApp.java
@Override public boolean onCreateOptionsMenu(final Menu menu) { MenuInflater inflater = getMenuInflater(); if (inflater != null && PrivacyService.checkClient()) { inflater.inflate(R.menu.app, menu); // Add all contact groups menu.findItem(R.id.menu_contacts).getSubMenu().add(-1, R.id.menu_contacts, Menu.NONE, getString(R.string.menu_all)); // Add other contact groups in the background new AsyncTask<Object, Object, Object>() { @Override/*from w w w . ja v a2 s .co m*/ protected Object doInBackground(Object... arg0) { try { String where = ContactsContract.Groups.GROUP_VISIBLE + " = 1"; where += " AND " + ContactsContract.Groups.SUMMARY_COUNT + " > 0"; Cursor cursor = getContentResolver().query(ContactsContract.Groups.CONTENT_SUMMARY_URI, new String[] { ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.ACCOUNT_NAME, ContactsContract.Groups.SUMMARY_COUNT }, where, null, ContactsContract.Groups.TITLE + ", " + ContactsContract.Groups.ACCOUNT_NAME); if (cursor != null) try { while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Groups._ID)); String title = cursor .getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)); String account = cursor .getString(cursor.getColumnIndex(ContactsContract.Groups.ACCOUNT_NAME)); menu.findItem(R.id.menu_contacts).getSubMenu().add(id, R.id.menu_contacts, Menu.NONE, title + "/" + account); } } finally { cursor.close(); } } catch (Throwable ex) { Util.bug(null, ex); } return null; } }.executeOnExecutor(mExecutor); return true; } else return false; }
From source file:com.clover.android.sdk.examples.InventoryTestActivity.java
private void fetchObjectsFromServiceConnector() { if (serviceIsBound && inventoryConnector != null) { new AsyncTask<Void, Void, Item>() { @Override protected Item doInBackground(Void... params) { Item item = null;/* w w w . j av a 2s .com*/ try { List<String> items = inventoryConnector.getItemIds(); if (items != null) { for (int i = 0; i < items.size(); i++) { String itemId = items.get(i); // just print out the first few to the console if (i > 10) { break; } item = inventoryConnector.getItem(itemId); Log.v(TAG, "item = " + dumpItem(item)); } // fetch tax rates, categories, modifier groups and modifiers and just print them to log for now List<Category> categories = inventoryConnector.getCategories(); if (categories != null) { for (Category category : categories) { Log.v(TAG, "category = " + dumpCategory(category)); } } List<TaxRate> taxRates = inventoryConnector.getTaxRates(); if (taxRates != null) { for (TaxRate taxRate : taxRates) { Log.v(TAG, "tax rate = " + dumpTaxRate(taxRate)); } } List<ModifierGroup> modifierGroups = inventoryConnector.getModifierGroups(); if (modifierGroups != null) { for (ModifierGroup modifierGroup : modifierGroups) { Log.v(TAG, "modifier group = " + dumpModifierGroup(modifierGroup)); List<Modifier> modifiers = inventoryConnector .getModifiers(modifierGroup.getId()); if (modifiers != null) { for (Modifier modifier : modifiers) { Log.v(TAG, "modifier = " + dumpModifier(modifier)); } } } } } } catch (ForbiddenException e) { Log.e(TAG, "Auth exception", e); } catch (ClientException e) { Log.e(TAG, "Client exception", e); } catch (ServiceException e) { Log.e(TAG, "Service exception", e); } catch (BindingException e) { Log.e(TAG, "Error calling inventory service", e); } catch (RemoteException e) { Log.e(TAG, "Error calling inventory service", e); } return item; } @Override protected void onPostExecute(Item result) { displayItem(result); } }.execute(); } }
From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java
protected Task<AccessToken> doGetAccessToken(final Twitter instance, Bundle bundle) { final Task<AccessToken>.TaskCompletionSource source = Task.create(); new AsyncTask<Bundle, Void, Object>() { @Override//from www . j a v a 2 s . co m protected Object doInBackground(Bundle... params) { try { Bundle result = params[0]; RequestToken token = (RequestToken) result.getSerializable("request_token"); String verifier = result.getString("oauth_verifier"); AccessToken accessToken = instance.getOAuthAccessToken(token, verifier); Log.d(BuildConfig.DEBUG_TAG, "accessToken.getScreenName() = " + accessToken.getScreenName()); Log.d(BuildConfig.DEBUG_TAG, "accessToken.getUserId() = " + accessToken.getUserId()); Log.d(BuildConfig.DEBUG_TAG, "accessToken.getToken() = " + accessToken.getToken()); Log.d(BuildConfig.DEBUG_TAG, "accessToken.getTokenSecret() = " + accessToken.getTokenSecret()); return accessToken; } catch (TwitterException e) { return e; } } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); if (o instanceof AccessToken) { source.trySetResult((AccessToken) o); } else { source.trySetError((Exception) o); } } }.execute(bundle); return source.getTask(); }