List of usage examples for twitter4j Twitter getHomeTimeline
ResponseList<Status> getHomeTimeline(Paging paging) throws TwitterException;
From source file:com.daiv.android.twitter.services.CatchupPull.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || !MainActivity.canSwitch) { return;//ww w .j ava 2s .c o m } CatchupPull.isRunning = true; Log.v("Test_pull", "catchup pull started"); sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); final Context context = getApplicationContext(); int unreadNow = sharedPrefs.getInt("pull_unread", 0); // stop it just in case context.sendBroadcast(new Intent("com.daiv.android.twitter.STOP_PUSH_SERVICE")); AppSettings settings = AppSettings.getInstance(context); if (settings.liveStreaming) { Log.v("Test_pull", "into the try for catchup service"); Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<Status> statuses = new ArrayList<Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[0]; } catch (Exception e) { context.startService(new Intent(context, TestPullNotificationService.class)); CatchupPull.isRunning = false; return; } try { paging.setSinceId(id); } catch (Exception e) { paging.setSinceId(1l); } for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("Test_inserting", "found status"); foundStatus = true; } else { Log.v("Test_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; e.printStackTrace(); } catch (OutOfMemoryError o) { // don't know why... o.printStackTrace(); } } Log.v("Test_pull", "got statuses, new = " + statuses.size()); // hash set to remove duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("Test_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); int inserted = dataSource.insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()) .commit(); unreadNow += statuses.size(); } if (settings.preCacheImages) { // delay it 15 seconds so that we can finish checking mentions first new Handler().postDelayed(new Runnable() { @Override public void run() { startService(new Intent(context, PreCacheService.class)); } }, 15000); } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); } try { Twitter twitter = Utils.getTwitter(context, settings); int currentAccount = sharedPrefs.getInt("current_account", 1); User user = twitter.verifyCredentials(); MentionsDataSource dataSource = MentionsDataSource.getInstance(context); long[] lastId = dataSource.getLastIds(currentAccount); Paging paging; paging = new Paging(1, 200); if (lastId[0] > 0) { paging.sinceId(lastId[0]); } List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging); int numNew = dataSource.insertTweets(statuses, currentAccount); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit(); if (settings.notifications && settings.mentionsNot && numNew > 0) { NotificationUtils.refreshNotification(context); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } sharedPrefs.edit().putInt("pull_unread", unreadNow).commit(); context.startService(new Intent(context, TestPullNotificationService.class)); context.sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); Log.v("Test_pull", "finished with the catchup service"); CatchupPull.isRunning = false; }
From source file:com.daiv.android.twitter.services.TimelineRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning) { return;// ww w .jav a2 s. c o m } if (MainActivity.canSwitch) { TimelineRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); Context context = getApplicationContext(); int numberNew = 0; AppSettings settings = AppSettings.getInstance(context); // if they have mobile data on and don't want to sync over mobile data if (intent.getBooleanExtra("on_start_refresh", false)) { } else if (Utils.getConnectionStatus(context) && !settings.syncMobile) { return; } Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId = null; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[1]; } catch (Exception e) { try { Thread.sleep(5000); } catch (InterruptedException i) { } TimelineRefreshService.isRunning = false; return; } if (id == 0) { id = 1; } try { paging.setSinceId(id); } catch (Exception e) { paging.setSinceId(1l); } for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("Test_inserting", "found status"); foundStatus = true; } else { Log.v("Test_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("Test_pull", "got statuses, new = " + statuses.size()); // hash set to check for duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("Test_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); Long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - sharedPrefs.getLong("last_timeline_insert", 0l) < 10000) { Log.v("Test_refresh", "don't insert the tweets on refresh"); sendBroadcast(new Intent("com.daiv.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", 0)); TimelineRefreshService.isRunning = false; context.getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); return; } else { sharedPrefs.edit().putLong("last_timeline_insert", currentTime).commit(); } int inserted = HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()) .commit(); } if (!intent.getBooleanExtra("on_start_refresh", false)) { sharedPrefs.edit().putBoolean("refresh_me", true).commit(); if (settings.notifications && (settings.timelineNot || settings.favoriteUserNotifications) && inserted > 0 && !intent.getBooleanExtra("from_launcher", false)) { NotificationUtils.refreshNotification(context, !settings.timelineNot); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } } else { Log.v("Test_refresh", "sending broadcast to fragment"); sendBroadcast( new Intent("com.daiv.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", inserted)); } sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); TimelineRefreshService.isRunning = false; } }
From source file:com.daiv.android.twitter.services.WidgetRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { // it is refreshing elsewhere, so don't start if (WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || CatchupPull.isRunning || !MainActivity.canSwitch) { return;//w w w .j av a 2s . c o m } WidgetRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_icon) .setTicker(getResources().getString(R.string.refreshing) + "...") .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(getResources().getString(R.string.refreshing_widget) + "...") .setProgress(100, 100, true) .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.drawer_sync_dark)); NotificationManager mNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(6, mBuilder.build()); Context context = getApplicationContext(); AppSettings settings = AppSettings.getInstance(context); // if they have mobile data on and don't want to sync over mobile data if (Utils.getConnectionStatus(context) && !settings.syncMobile) { return; } Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[0]; } catch (Exception e) { WidgetRefreshService.isRunning = false; return; } paging.setSinceId(id); for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("Test_inserting", "found status"); foundStatus = true; } else { Log.v("Test_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("Test_pull", "got statuses, new = " + statuses.size()); // hash set to remove duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("Test_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); int inserted = HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()).commit(); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } context.sendBroadcast(new Intent("com.daiv.android.Test.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); mNotificationManager.cancel(6); WidgetRefreshService.isRunning = false; }
From source file:com.javielinux.api.loaders.LoadMoreTweetDownLoader.java
License:Apache License
@Override public BaseResponse loadInBackground() { try {// w w w.ja v a 2s. c o m LoadMoreTweetDownResponse response = new LoadMoreTweetDownResponse(); PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext()); int maxDownloadTweet = Integer.parseInt(pref.getString("prf_n_max_download", "60")); if (maxDownloadTweet <= 0) maxDownloadTweet = 60; ConnectionManager.getInstance().open(getContext()); Twitter twitter = ConnectionManager.getInstance().getTwitter(request.getUserId()); Paging p = new Paging(); p.setCount(maxDownloadTweet); p.setSinceId(request.getSinceId()); p.setMaxId(request.getMaxId()); ResponseList<Status> statii = null; try { statii = twitter.getHomeTimeline(p); } catch (OutOfMemoryError e) { e.printStackTrace(); } boolean breakTimeline = false; if (statii != null && statii.size() >= maxDownloadTweet - 10) { p = new Paging(1, 10); p.setSinceId(request.getSinceId()); p.setMaxId(statii.get(statii.size() - 1).getId()); if (twitter.getHomeTimeline().size() > 0) { breakTimeline = true; response.setHasMoreTweets(true); } } if (statii != null) { if (statii.size() > 0) { try { DataFramework.getInstance().open(getContext(), Utils.packageName); } catch (Exception e) { e.printStackTrace(); } List<InfoTweet> tweets = new ArrayList<InfoTweet>(); for (Status status : statii) { tweets.add(new InfoTweet(status)); } response.setTweets(tweets); long nextId = 1; Cursor c = DataFramework.getInstance().getCursor("tweets_user", new String[] { DataFramework.KEY_ID }, null, null, null, null, DataFramework.KEY_ID + " desc", "1"); if (!c.moveToFirst()) { c.close(); nextId = 1; } else { long Id = c.getInt(0) + 1; c.close(); nextId = Id; } try { boolean isFirst = true; for (int i = statii.size() - 1; i >= 0; i--) { User u = statii.get(i).getUser(); if (u != null) { ContentValues args = new ContentValues(); args.put(DataFramework.KEY_ID, "" + nextId); args.put("type_id", TweetTopicsUtils.TWEET_TYPE_TIMELINE); args.put("user_tt_id", "" + request.getUserId()); if (u.getProfileImageURL() != null) { args.put("url_avatar", u.getProfileImageURL().toString()); } else { args.put("url_avatar", ""); } args.put("username", u.getScreenName()); args.put("fullname", u.getName()); args.put("user_id", "" + u.getId()); args.put("tweet_id", Utils.fillZeros("" + statii.get(i).getId())); args.put("source", statii.get(i).getSource()); args.put("to_username", statii.get(i).getInReplyToScreenName()); args.put("to_user_id", "" + statii.get(i).getInReplyToUserId()); args.put("date", String.valueOf(statii.get(i).getCreatedAt().getTime())); if (statii.get(i).getRetweetedStatus() != null) { args.put("is_retweet", 1); args.put("retweet_url_avatar", statii.get(i).getRetweetedStatus().getUser() .getProfileImageURL().toString()); args.put("retweet_username", statii.get(i).getRetweetedStatus().getUser().getScreenName()); args.put("retweet_source", statii.get(i).getRetweetedStatus().getSource()); String t = Utils.getTwitLoger(statii.get(i).getRetweetedStatus()); if (t.equals("")) { args.put("text", statii.get(i).getRetweetedStatus().getText()); args.put("text_urls", Utils.getTextURLs(statii.get(i).getRetweetedStatus())); } else { args.put("text", t); } args.put("is_favorite", 0); } else { String t = Utils.getTwitLoger(statii.get(i)); if (t.equals("")) { args.put("text", statii.get(i).getText()); args.put("text_urls", Utils.getTextURLs(statii.get(i))); } else { args.put("text", t); } if (statii.get(i).isFavorited()) { args.put("is_favorite", 1); } } if (statii.get(i).getGeoLocation() != null) { args.put("latitude", statii.get(i).getGeoLocation().getLatitude()); args.put("longitude", statii.get(i).getGeoLocation().getLongitude()); } args.put("reply_tweet_id", statii.get(i).getInReplyToStatusId()); if (breakTimeline && isFirst) args.put("has_more_tweets_down", 1); DataFramework.getInstance().getDB().insert("tweets_user", null, args); nextId++; if (isFirst) isFirst = false; } } } catch (SQLException e) { e.printStackTrace(); } DataFramework.getInstance().close(); } } return response; } catch (TwitterException twitterException) { twitterException.printStackTrace(); ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setError(twitterException, twitterException.getMessage()); return errorResponse; } catch (Exception exception) { exception.printStackTrace(); ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setError(exception, exception.getMessage()); return errorResponse; } }
From source file:com.javielinux.database.EntityTweetUser.java
License:Apache License
public InfoSaveTweets saveTweets(Context context, Twitter twitter) { InfoSaveTweets out = new InfoSaveTweets(); try {//from w w w .j av a 2s . c o m String where = "type_id = " + tweet_type + " AND user_tt_id=" + getId(); int nResult = DataFramework.getInstance().getEntityListCount("tweets_user", where); if (nResult > 0) mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets_user", where, "date desc") .getLong("tweet_id"); boolean breakTimeline = false; PreferenceManager.setDefaultValues(context, R.xml.preferences, false); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); int maxDownloadTweet = Integer.parseInt(pref.getString("prf_n_max_download", "60")); if (maxDownloadTweet <= 0) maxDownloadTweet = 60; ResponseList<twitter4j.Status> statii = null; ResponseList<twitter4j.DirectMessage> directs = null; if (mLastIdNotification > 0) { if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) { Paging p = new Paging(1, maxDownloadTweet); p.setSinceId(mLastIdNotification); try { statii = twitter.getHomeTimeline(p); } catch (OutOfMemoryError e) { e.printStackTrace(); } if (statii != null && statii.size() >= maxDownloadTweet - 10) { p = new Paging(1, 10); p.setSinceId(mLastIdNotification); p.setMaxId(statii.get(statii.size() - 1).getId()); if (twitter.getHomeTimeline().size() > 0) { breakTimeline = true; } } } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) { Paging p = new Paging(); p.setCount(100); p.setSinceId(mLastIdNotification); statii = twitter.getMentionsTimeline(p); } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) { Paging p = new Paging(); p.setCount(100); p.setSinceId(mLastIdNotification); directs = twitter.getDirectMessages(p); } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) { Paging p = new Paging(); p.setCount(100); p.setSinceId(mLastIdNotification); directs = twitter.getSentDirectMessages(p); } } else { try { Log.d(Utils.TAG, "Primera carga de " + getTypeText()); if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) { statii = twitter.getHomeTimeline(new Paging(1, 40)); } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) { statii = twitter.getMentionsTimeline(new Paging(1, 40)); } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) { directs = twitter.getDirectMessages(); } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) { directs = twitter.getSentDirectMessages(); } } catch (OutOfMemoryError e) { e.printStackTrace(); } } // guardar statii if (statii != null) { if (statii.size() > 0) { out.setNewMessages(statii.size()); out.setNewerId(statii.get(0).getId()); out.setOlderId(statii.get(statii.size() - 1).getId()); Log.d(Utils.TAG, statii.size() + " mensajes nuevos en " + getTypeText() + " de " + getString("name")); long nextId = 1; Cursor c = DataFramework.getInstance().getCursor("tweets_user", new String[] { DataFramework.KEY_ID }, null, null, null, null, DataFramework.KEY_ID + " desc", "1"); if (!c.moveToFirst()) { c.close(); nextId = 1; } else { long Id = c.getInt(0) + 1; c.close(); nextId = Id; } DataFramework.getInstance().getDB().beginTransaction(); try { boolean isFirst = true; for (int i = statii.size() - 1; i >= 0; i--) { User u = statii.get(i).getUser(); if (u != null) { ContentValues args = new ContentValues(); args.put(DataFramework.KEY_ID, "" + nextId); args.put("type_id", tweet_type); args.put("user_tt_id", "" + getId()); if (u.getProfileImageURL() != null) { args.put("url_avatar", u.getProfileImageURL().toString()); } else { args.put("url_avatar", ""); } args.put("username", u.getScreenName()); args.put("fullname", u.getName()); args.put("user_id", "" + u.getId()); args.put("tweet_id", Utils.fillZeros("" + statii.get(i).getId())); args.put("source", statii.get(i).getSource()); args.put("to_username", statii.get(i).getInReplyToScreenName()); args.put("to_user_id", "" + statii.get(i).getInReplyToUserId()); args.put("date", String.valueOf(statii.get(i).getCreatedAt().getTime())); if (statii.get(i).getRetweetedStatus() != null) { args.put("is_retweet", 1); args.put("retweet_url_avatar", statii.get(i).getRetweetedStatus().getUser() .getProfileImageURL().toString()); args.put("retweet_username", statii.get(i).getRetweetedStatus().getUser().getScreenName()); args.put("retweet_source", statii.get(i).getRetweetedStatus().getSource()); String t = Utils.getTwitLoger(statii.get(i).getRetweetedStatus()); if (t.equals("")) { args.put("text", statii.get(i).getRetweetedStatus().getText()); args.put("text_urls", Utils.getTextURLs(statii.get(i).getRetweetedStatus())); } else { args.put("text", t); } args.put("is_favorite", 0); } else { String t = Utils.getTwitLoger(statii.get(i)); if (t.equals("")) { args.put("text", statii.get(i).getText()); args.put("text_urls", Utils.getTextURLs(statii.get(i))); } else { args.put("text", t); } if (statii.get(i).isFavorited()) { args.put("is_favorite", 1); } } if (statii.get(i).getGeoLocation() != null) { args.put("latitude", statii.get(i).getGeoLocation().getLatitude()); args.put("longitude", statii.get(i).getGeoLocation().getLongitude()); } args.put("reply_tweet_id", statii.get(i).getInReplyToStatusId()); if (breakTimeline && isFirst) args.put("has_more_tweets_down", 1); DataFramework.getInstance().getDB().insert("tweets_user", null, args); out.addId(nextId); nextId++; if (isFirst) isFirst = false; } } // finalizar int total = nResult + statii.size(); if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH || total > Utils.MAX_ROW_BYSEARCH_FORCE) { try { Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente " + total + " registros"); String date = DataFramework.getInstance() .getEntityList("tweets_user", "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc") .get(Utils.MAX_ROW_BYSEARCH).getString("date"); String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type + " and user_tt_id=" + getId() + " AND date < '" + date + "'"; DataFramework.getInstance().getDB().execSQL(sqldelete); } catch (OutOfMemoryError e) { } } DataFramework.getInstance().getDB().setTransactionSuccessful(); } catch (SQLException e) { e.printStackTrace(); } finally { DataFramework.getInstance().getDB().endTransaction(); } } } // guardar directs if (directs != null) { if (directs.size() > 0) { out.setNewMessages(directs.size()); out.setNewerId(directs.get(0).getId()); out.setOlderId(directs.get(directs.size() - 1).getId()); Log.d(Utils.TAG, directs.size() + " mensajes directos a " + getString("name")); long nextId = 1; Cursor c = DataFramework.getInstance().getCursor("tweets_user", new String[] { DataFramework.KEY_ID }, null, null, null, null, DataFramework.KEY_ID + " desc", "1"); if (!c.moveToFirst()) { c.close(); nextId = 1; } else { long Id = c.getInt(0) + 1; c.close(); nextId = Id; } DataFramework.getInstance().getDB().beginTransaction(); try { for (int i = directs.size() - 1; i >= 0; i--) { User u = directs.get(i).getSender(); if (u != null) { ContentValues args = new ContentValues(); args.put(DataFramework.KEY_ID, "" + nextId); args.put("type_id", tweet_type); args.put("user_tt_id", "" + getId()); if (u.getProfileImageURL() != null) { args.put("url_avatar", u.getProfileImageURL().toString()); } else { args.put("url_avatar", ""); } args.put("username", u.getScreenName()); args.put("fullname", u.getName()); args.put("user_id", "" + u.getId()); args.put("tweet_id", Utils.fillZeros("" + directs.get(i).getId())); args.put("source", ""); args.put("to_username", directs.get(i).getRecipientScreenName()); args.put("to_user_id", "" + directs.get(i).getRecipientId()); args.put("date", String.valueOf(directs.get(i).getCreatedAt().getTime())); args.put("text", directs.get(i).getText()); DataFramework.getInstance().getDB().insert("tweets_user", null, args); out.addId(nextId); Log.d(Utils.TAG, "getRecipientScreenName: " + directs.get(i).getRecipientScreenName()); nextId++; } } // finalizar int total = nResult + directs.size(); if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH) { Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente " + total + " registros"); String date = DataFramework.getInstance() .getEntityList("tweets_user", "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc") .get(Utils.MAX_ROW_BYSEARCH).getString("date"); String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type + " and user_tt_id=" + getId() + " AND date < '" + date + "'"; DataFramework.getInstance().getDB().execSQL(sqldelete); } DataFramework.getInstance().getDB().setTransactionSuccessful(); } catch (SQLException e) { e.printStackTrace(); } finally { DataFramework.getInstance().getDB().endTransaction(); } } } } catch (TwitterException e) { e.printStackTrace(); RateLimitStatus rate = e.getRateLimitStatus(); if (rate != null) { out.setError(Utils.LIMIT_ERROR); out.setRate(rate); } else { out.setError(Utils.UNKNOWN_ERROR); } } catch (Exception e) { e.printStackTrace(); out.setError(Utils.UNKNOWN_ERROR); } return out; }
From source file:com.klinker.android.twitter.services.CatchupPull.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || !MainActivity.canSwitch) { return;//from ww w. ja v a2 s.com } CatchupPull.isRunning = true; Log.v("talon_pull", "catchup pull started"); sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); final Context context = getApplicationContext(); int unreadNow = sharedPrefs.getInt("pull_unread", 0); // stop it just in case context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE")); AppSettings settings = AppSettings.getInstance(context); if (settings.liveStreaming) { Log.v("talon_pull", "into the try for catchup service"); Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<Status> statuses = new ArrayList<Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[0]; } catch (Exception e) { context.startService(new Intent(context, TalonPullNotificationService.class)); CatchupPull.isRunning = false; return; } try { paging.setSinceId(id); } catch (Exception e) { paging.setSinceId(1l); } for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("talon_inserting", "found status"); foundStatus = true; } else { Log.v("talon_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; e.printStackTrace(); } catch (OutOfMemoryError o) { // don't know why... o.printStackTrace(); } } Log.v("talon_pull", "got statuses, new = " + statuses.size()); // hash set to remove duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("talon_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); int inserted = dataSource.insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()) .commit(); unreadNow += statuses.size(); } if (settings.preCacheImages) { // delay it 15 seconds so that we can finish checking mentions first new Handler().postDelayed(new Runnable() { @Override public void run() { startService(new Intent(context, PreCacheService.class)); } }, 15000); } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); } try { Twitter twitter = Utils.getTwitter(context, settings); int currentAccount = sharedPrefs.getInt("current_account", 1); User user = twitter.verifyCredentials(); MentionsDataSource dataSource = MentionsDataSource.getInstance(context); long[] lastId = dataSource.getLastIds(currentAccount); Paging paging; paging = new Paging(1, 200); if (lastId[0] > 0) { paging.sinceId(lastId[0]); } List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging); int numNew = dataSource.insertTweets(statuses, currentAccount); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit(); if (settings.notifications && settings.mentionsNot && numNew > 0) { NotificationUtils.refreshNotification(context); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } sharedPrefs.edit().putInt("pull_unread", unreadNow).commit(); context.startService(new Intent(context, TalonPullNotificationService.class)); context.sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); Log.v("talon_pull", "finished with the catchup service"); CatchupPull.isRunning = false; }
From source file:com.klinker.android.twitter.services.TimelineRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { if (!MainActivity.canSwitch || CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning) { return;/* www. j a va 2s . c om*/ } if (MainActivity.canSwitch) { TimelineRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); Context context = getApplicationContext(); int numberNew = 0; AppSettings settings = AppSettings.getInstance(context); // if they have mobile data on and don't want to sync over mobile data if (intent.getBooleanExtra("on_start_refresh", false)) { } else if (Utils.getConnectionStatus(context) && !settings.syncMobile) { return; } Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId = null; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[1]; } catch (Exception e) { try { Thread.sleep(5000); } catch (InterruptedException i) { } TimelineRefreshService.isRunning = false; return; } if (id == 0) { id = 1; } try { paging.setSinceId(id); } catch (Exception e) { paging.setSinceId(1l); } for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("talon_inserting", "found status"); foundStatus = true; } else { Log.v("talon_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("talon_pull", "got statuses, new = " + statuses.size()); // hash set to check for duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("talon_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); Long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - sharedPrefs.getLong("last_timeline_insert", 0l) < 10000) { Log.v("talon_refresh", "don't insert the tweets on refresh"); sendBroadcast( new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", 0)); TimelineRefreshService.isRunning = false; return; } else { sharedPrefs.edit().putLong("last_timeline_insert", currentTime).commit(); } int inserted = HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()) .commit(); } if (!intent.getBooleanExtra("on_start_refresh", false)) { sharedPrefs.edit().putBoolean("refresh_me", true).commit(); if (settings.notifications && settings.timelineNot && inserted > 0 && !intent.getBooleanExtra("from_launcher", false)) { NotificationUtils.refreshNotification(context); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } } else { Log.v("talon_refresh", "sending broadcast to fragment"); sendBroadcast(new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", inserted)); } sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); TimelineRefreshService.isRunning = false; } }
From source file:com.klinker.android.twitter.services.WidgetRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { // it is refreshing elsewhere, so don't start if (WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || CatchupPull.isRunning || !MainActivity.canSwitch) { return;// w ww . ja v a2 s . c om } WidgetRefreshService.isRunning = true; sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_icon) .setTicker(getResources().getString(R.string.refreshing) + "...") .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(getResources().getString(R.string.refreshing_widget) + "...") .setProgress(100, 100, true) .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.drawer_sync_dark)); NotificationManager mNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(6, mBuilder.build()); Context context = getApplicationContext(); AppSettings settings = AppSettings.getInstance(context); // if they have mobile data on and don't want to sync over mobile data if (Utils.getConnectionStatus(context) && !settings.syncMobile) { return; } Twitter twitter = Utils.getTwitter(context, settings); HomeDataSource dataSource = HomeDataSource.getInstance(context); int currentAccount = sharedPrefs.getInt("current_account", 1); List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>(); boolean foundStatus = false; Paging paging = new Paging(1, 200); long[] lastId; long id; try { lastId = dataSource.getLastIds(currentAccount); id = lastId[0]; } catch (Exception e) { WidgetRefreshService.isRunning = false; return; } paging.setSinceId(id); for (int i = 0; i < settings.maxTweetsRefresh; i++) { try { if (!foundStatus) { paging.setPage(i + 1); List<Status> list = twitter.getHomeTimeline(paging); statuses.addAll(list); if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) { Log.v("talon_inserting", "found status"); foundStatus = true; } else { Log.v("talon_inserting", "haven't found status"); foundStatus = false; } } } catch (Exception e) { // the page doesn't exist foundStatus = true; } catch (OutOfMemoryError o) { // don't know why... } } Log.v("talon_pull", "got statuses, new = " + statuses.size()); // hash set to remove duplicates I guess HashSet hs = new HashSet(); hs.addAll(statuses); statuses.clear(); statuses.addAll(hs); Log.v("talon_inserting", "tweets after hashset: " + statuses.size()); lastId = dataSource.getLastIds(currentAccount); int inserted = HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId); if (inserted > 0 && statuses.size() > 0) { sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()).commit(); } if (settings.preCacheImages) { startService(new Intent(this, PreCacheService.class)); } context.sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET")); getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); mNotificationManager.cancel(6); WidgetRefreshService.isRunning = false; }
From source file:com.mothsoft.integration.twitter.TwitterServiceImpl.java
License:Apache License
@SuppressWarnings("deprecation") public List<Status> getHomeTimeline(AccessToken accessToken, Long sinceId, Short maximumNumber) { final Twitter twitter = this.factory.getInstance(accessToken); final List<Status> statuses = new ArrayList<Status>(maximumNumber); // default maximum number to 200 if null maximumNumber = maximumNumber == null ? 200 : maximumNumber; // default page size to lesser of maximumNumber, 200 final int pageSize = maximumNumber > 200 ? 200 : maximumNumber; int page = 0; while (statuses.size() < maximumNumber) { Paging paging = new Paging(++page, pageSize); final ResponseList temp; if (sinceId != null) { paging = paging.sinceId(sinceId); }//from ww w .j a v a 2 s . co m try { temp = twitter.getHomeTimeline(paging); } catch (TwitterException e) { throw this.wrapException(e); } // break out as soon as we get a page smaller than the designated // page size if (temp.size() == 0) { break; } else { statuses.addAll(temp); } // check rate limit status and warn or skip remaining fetches as // appropriate final RateLimitStatus rateLimitStatus = temp.getRateLimitStatus(); if (rateLimitStatus.getRemaining() < (.1 * rateLimitStatus.getLimit())) { logger.warn("Twitter rate limit approaching. Calls remaining: " + rateLimitStatus.getRemaining()); } if (rateLimitStatus.getRemainingHits() == 0) { final Date resetTime = new Date( System.currentTimeMillis() + (rateLimitStatus.getSecondsUntilReset() * 1000)); logger.error("Twitter rate limit hit. Will reset at: " + resetTime.toLocaleString()); break; } } return statuses; }
From source file:com.stronquens.amgtwitter.ControllerTwitter.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w. j a v a2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Obtenemos parametros de la peticion String op = request.getParameter("op"); String accesToken = request.getParameter("token"); String accesTokenSecret = request.getParameter("secret"); // Inicializamos variables String jsonResult = ""; Twitter twitter = null; ConfigurationBuilder configBuilder = new ConfigurationBuilder(); Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create(); // Se crea la instancia de twitter segun los parametros de ususario if (!"".equalsIgnoreCase(accesToken) && !"".equalsIgnoreCase(accesTokenSecret)) { try { configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf") .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW") .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret); twitter = new TwitterFactory(configBuilder.build()).getInstance(); } catch (Exception e) { System.out.println(e); } } else { try { configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf") .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW"); twitter = new TwitterFactory(configBuilder.build()).getInstance(); } catch (Exception e) { System.out.println(e); } } // Se realizan las diferentes operaciones switch (op) { case "timeline": try { Paging pagina = new Paging(); pagina.setCount(25); ResponseList listado = twitter.getHomeTimeline(pagina); jsonResult = gson.toJson(listado); } catch (TwitterException ex) { System.out.println(ex); } break; case "usersettings": try { jsonResult = gson.toJson(twitter.showUser(twitter.getId())); } catch (TwitterException ex) { System.out.println(ex); } break; case "pruebas": try { jsonResult = gson.toJson(twitter.showUser(twitter.getId())); } catch (TwitterException ex) { System.out.println(ex); } break; default: jsonResult = "{\"eror\":\"la operacion no existe\"}"; } // Se devuelven los valores out.println(jsonResult); } }