List of usage examples for android.os AsyncTask execute
@MainThread public static void execute(Runnable runnable)
From source file:cz.maresmar.sfm.view.portal.PortalDetailFragment.java
@Override public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) { switch (loader.getId()) { case PORTAL_LOADER_ID: Timber.d("Portal data loaded"); cursor.moveToFirst();//from w w w .j a v a2 s . c o m if (BuildConfig.DEBUG) { Assert.isOne(cursor.getCount()); } // Portal name mNameText.setText(cursor.getString(0)); // Portal reference mRefText.setText(cursor.getString(1)); // Security spinner setConnectionSecurity(cursor.getInt(3)); // Location LatLng location = new LatLng(cursor.getDouble(4), cursor.getDouble(5)); if (location.latitude == 0 && location.longitude == 0) removeLocation(); else setLocation(location); // Extra setExtraData(cursor.getString(6)); // Plugin String plugin = cursor.getString(2); AsyncTask.execute(() -> { try { blockingLoaders.await(); } catch (InterruptedException e) { Timber.e(e); } getActivity().runOnUiThread(() -> { setPlugin(plugin); mPluginSpinner.setOnItemSelectedListener(mPluginChangeListen); }); }); // New menu notification @ProviderContract.PortalFlags int flags = cursor.getInt(7); mNewMenuNotificationCheckBox.setChecked(!((flags & ProviderContract.PORTAL_FLAG_DISABLE_NEW_MENU_NOTIFICATION) == ProviderContract.PORTAL_FLAG_DISABLE_NEW_MENU_NOTIFICATION)); break; default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } }
From source file:com.piusvelte.sonet.core.SonetService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else/*w ww. j a v a 2 s. c o m*/ putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(SonetService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(SonetService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(SonetService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(SonetService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Sonet.default_message_bg_color; int profile_bg_color = Sonet.default_message_bg_color; int friend_bg_color = Sonet.default_friend_bg_color; boolean icon = true; int status_count = Sonet.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(SonetService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Sonet.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(SonetService.this, widget, Sonet.INVALID_ACCOUNT_ID); } initAccountSettings(SonetService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(SonetService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(SonetService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(SonetService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(SonetService.this, 0, (Sonet .getPackageIntent(SonetService.this, SonetNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:com.shafiq.myfeedle.core.MyfeedleService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else//from w w w . j a va2 s. c om putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(MyfeedleService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(MyfeedleService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(MyfeedleService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Myfeedle.default_message_bg_color; int profile_bg_color = Myfeedle.default_message_bg_color; int friend_bg_color = Myfeedle.default_friend_bg_color; boolean icon = true; int status_count = Myfeedle.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(MyfeedleService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Myfeedle.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(MyfeedleService.this, widget, Myfeedle.INVALID_ACCOUNT_ID); } initAccountSettings(MyfeedleService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(MyfeedleService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(MyfeedleService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(MyfeedleService.this, 0, (Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:com.facebook.android.friendsmash.HomeFragment.java
private void postScore() { final int score = application.getScore(); if (score > 0) { // Only post the score if they smashed at least one friend! // Post the score to our servers for the high score table AsyncTask.execute(new Runnable() { public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://www.friendsmash.com/scores"); try { // Add data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("fbid", application.getCurrentFBUser().getId())); nameValuePairs.add(new BasicNameValuePair("score", "" + score)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute the HTTP Post request and log the result HttpResponse responsePost = httpClient.execute(httpPost); HttpEntity responseEntity = responsePost.getEntity(); String response = EntityUtils.toString(responseEntity); Log.i(FriendSmashApplication.TAG, "Score post to server: " + response); } catch (Exception e) { Log.e(FriendSmashApplication.TAG, e.toString()); Log.e(FriendSmashApplication.TAG, "Posting Score to Server failed: " + e.getMessage()); }//from w w w . ja va2s. c om } }); } }
From source file:com.support.android.designlibdemo.PetsDetailActivity.java
/**********************************************************************************************/ private static void loadImageFromUrl(final String url) { AsyncTask.execute(new Runnable() { @Override// ww w . j av a 2 s.co m public void run() { sharedImage = getBitmapFromURL(url); } }); }
From source file:com.nappking.movietimesup.GameFragment.java
private void fetchFriendBitmapAndFireImages(final UserImageView userImageView, final String friendToSmashID, final boolean extraImage) { AsyncTask.execute(new Runnable() { public void run() { URL bitmapURL;// w w w. j a v a2s . c o m try { bitmapURL = new URL("http://graph.facebook.com/" + friendToSmashID + "/picture?width=" + iconWidth + "&height=" + iconWidth); friendToSmashBitmap = BitmapFactory.decodeStream(bitmapURL.openConnection().getInputStream()); } catch (Exception e) { // Unknown error Log.e(FriendSmashApplication.TAG, e.toString()); } uiHandler.post(new Runnable() { @Override public void run() { // Hide the spinner after retrieving progressContainer.setVisibility(View.INVISIBLE); if (friendToSmashBitmap != null) { setFriendImageAndFire(userImageView, friendToSmashBitmap, extraImage); // Also set the lastFriendSmashedID in the application ((FriendSmashApplication) getActivity().getApplication()) .setLastFriendSmashedID(friendToSmashID); } else { closeAndShowError(getResources().getString(R.string.error_fetching_friend_bitmap)); } } }); } }); }
From source file:org.getlantern.firetweet.fragment.support.MessagesConversationFragment.java
public void showConversation(final ParcelableAccount account, final ParcelableUser recipient) { mAccount = account;/* w w w .j av a 2s .c o m*/ mRecipient = recipient; if (account == null || recipient == null) return; final LoaderManager lm = getLoaderManager(); final Bundle args = new Bundle(); args.putLong(EXTRA_ACCOUNT_ID, account.account_id); args.putLong(EXTRA_RECIPIENT_ID, recipient.id); if (mLoaderInitialized) { lm.restartLoader(0, args, this); } else { mLoaderInitialized = true; lm.initLoader(0, args, this); } AsyncTask.execute(new Runnable() { @Override public void run() { } }); new SetReadStateTask(getActivity(), account, recipient).execute(); updateActionBar(); updateProfileImage(); }
From source file:com.nappking.movietimesup.HomeFragment.java
private void postScore() { final int score = application.getScore(); if (score > 0) { // Only post the score if they smashed at least one friend! // Post the score to FB (for score stories and distribution) Bundle fbParams = new Bundle(); fbParams.putString("score", "" + score); Request postScoreRequest = new Request(Session.getActiveSession(), "me/scores", fbParams, HttpMethod.POST, new Request.Callback() { @Override/*from w w w . ja v a 2 s . c o m*/ public void onCompleted(Response response) { FacebookRequestError error = response.getError(); if (error != null) { Log.e(FriendSmashApplication.TAG, "Posting Score to Facebook failed: " + error.getErrorMessage()); ((HomeActivity) getActivity()).handleError(error, false); } else { Log.i(FriendSmashApplication.TAG, "Score posted successfully to Facebook"); } } }); Request.executeBatchAsync(postScoreRequest); // Post the score to our servers for the high score table AsyncTask.execute(new Runnable() { public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://www.friendsmash.com/scores"); try { // Add data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("fbid", application.getCurrentFBUser().getId())); nameValuePairs.add(new BasicNameValuePair("score", "" + score)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute the HTTP Post request and log the result HttpResponse responsePost = httpClient.execute(httpPost); HttpEntity responseEntity = responsePost.getEntity(); String response = EntityUtils.toString(responseEntity); Log.i(FriendSmashApplication.TAG, "Score post to server: " + response); } catch (Exception e) { Log.e(FriendSmashApplication.TAG, e.toString()); Log.e(FriendSmashApplication.TAG, "Posting Score to Server failed: " + e.getMessage()); } } }); } }
From source file:com.piusvelte.sonet.core.SonetNotifications.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/* w w w. j a va 2s .co 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(SonetNotifications.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()) { mSonetCrypto = SonetCrypto.getInstance(getApplicationContext()); HttpClient httpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext()); while (!widgets.isAfterLast()) { long accountId = widgets.getLong(0); ArrayList<String> notificationSids = new ArrayList<String>(); Cursor account = getContentResolver().query( Accounts.getContentUri(SonetNotifications.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 = mSonetCrypto.Decrypt(account.getString(0)); String secret = mSonetCrypto.Decrypt(account.getString(1)); int service = account.getInt(2); String accountEsid = mSonetCrypto.Decrypt(account.getString(3)); mSimpleDateFormat = null; if (service == TWITTER) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(SonetNotifications.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 = mSonetCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status SonetOAuth sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(SonetNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mSonetCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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(SonetNotifications.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 = mSonetCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status SonetOAuth sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(SonetNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mSonetCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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(SonetNotifications.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; SonetOAuth sonetOAuth; switch (service) { case FACEBOOK: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .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 = SonetHttpClient.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( SonetNotifications.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 = SonetHttpClient.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: sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; String esid = mSonetCrypto .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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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( SonetNotifications.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 = SonetHttpClient .httpResponse(httpClient, sonetOAuth.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 = mSonetCrypto .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 = SonetHttpClient.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( SonetNotifications.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 = SonetHttpClient.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: sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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( SonetNotifications.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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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 = SonetHttpClient.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 = mSonetCrypto .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 = SonetHttpClient.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 = SonetHttpClient.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(SonetNotifications.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); SonetNotifications.this.getContentResolver() .update(Notifications.getContentUri(SonetNotifications.this), values, null, null); return true; } return false; } @Override protected void onProgressUpdate(String... messages) { (Toast.makeText(SonetNotifications.this, messages[0], Toast.LENGTH_LONG)).show(); } @Override protected void onPostExecute(Boolean finish) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } if (finish) { SonetNotifications.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(SonetNotifications.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.SonetNotifications.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// w w w . j ava2 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(SonetNotifications.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()) { mSonetCrypto = SonetCrypto.getInstance(getApplicationContext()); HttpClient httpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext()); while (!widgets.isAfterLast()) { long accountId = widgets.getLong(0); ArrayList<String> notificationSids = new ArrayList<String>(); Cursor account = getContentResolver().query( Accounts.getContentUri(SonetNotifications.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 = mSonetCrypto.Decrypt(account.getString(0)); String secret = mSonetCrypto.Decrypt(account.getString(1)); int service = account.getInt(2); String accountEsid = mSonetCrypto.Decrypt(account.getString(3)); mSimpleDateFormat = null; if (service == TWITTER) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(SonetNotifications.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 = mSonetCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(SonetNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mSonetCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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(SonetNotifications.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 = mSonetCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(SonetNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mSonetCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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(SonetNotifications.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; SonetOAuth sonetOAuth; switch (service) { case FACEBOOK: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .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 = SonetHttpClient.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( SonetNotifications.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 = SonetHttpClient.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: sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; String esid = mSonetCrypto .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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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( SonetNotifications.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 = SonetHttpClient .httpResponse(httpClient, sonetOAuth.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 = mSonetCrypto .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 = SonetHttpClient.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( SonetNotifications.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 = SonetHttpClient.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: sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mSonetCrypto .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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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( SonetNotifications.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 = SonetHttpClient.httpResponse(httpClient, sonetOAuth.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", BuildConfig.GOOGLECLIENT_ID)); httpParams.add(new BasicNameValuePair("client_secret", BuildConfig.GOOGLECLIENT_SECRET)); httpParams.add(new BasicNameValuePair("refresh_token", token)); httpParams.add(new BasicNameValuePair("grant_type", "refresh_token")); try { httpPost.setEntity(new UrlEncodedFormEntity(httpParams)); if ((response = SonetHttpClient.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 = mSonetCrypto .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 = SonetHttpClient.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 = SonetHttpClient.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(SonetNotifications.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); SonetNotifications.this.getContentResolver() .update(Notifications.getContentUri(SonetNotifications.this), values, null, null); return true; } return false; } @Override protected void onProgressUpdate(String... messages) { (Toast.makeText(SonetNotifications.this, messages[0], Toast.LENGTH_LONG)).show(); } @Override protected void onPostExecute(Boolean finish) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } if (finish) { SonetNotifications.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(SonetNotifications.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); }