List of usage examples for twitter4j Twitter verifyCredentials
User verifyCredentials() throws TwitterException;
From source file:com.daiv.android.twitter.services.DirectMessageRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); 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;/*from w ww. ja va 2 s.c om*/ } boolean update = false; int numberNew = 0; try { Twitter twitter = Utils.getTwitter(context, settings); int currentAccount = sharedPrefs.getInt("current_account", 1); User user = twitter.verifyCredentials(); long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0); Paging paging; if (lastId != 0) { paging = new Paging(1).sinceId(lastId); } else { paging = new Paging(1, 500); } List<DirectMessage> dm = twitter.getDirectMessages(paging); List<DirectMessage> sent = twitter.getSentDirectMessages(paging); if (dm.size() != 0) { sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit(); numberNew = dm.size(); } else { numberNew = 0; } DMDataSource dataSource = DMDataSource.getInstance(context); int inserted = 0; for (DirectMessage directMessage : dm) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } inserted++; } for (DirectMessage directMessage : sent) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit(); if (settings.notifications && settings.dmsNot && inserted > 0) { int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0); sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit(); NotificationUtils.refreshNotification(context); } if (settings.syncSecondMentions) { startService(new Intent(context, SecondDMRefreshService.class)); } sendBroadcast(new Intent("com.daiv.android.twitter.NEW_DIRECT_MESSAGE")); } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } }
From source file:com.daiv.android.twitter.services.SecondDMRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); 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;//from www. j av a2 s . c om } boolean update = false; int numberNew = 0; try { Twitter twitter = Utils.getSecondTwitter(context); int currentAccount = sharedPrefs.getInt("current_account", 1); if (currentAccount == 1) { currentAccount = 2; } else { currentAccount = 1; } User user = twitter.verifyCredentials(); long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0); Paging paging; if (lastId != 0) { paging = new Paging(1).sinceId(lastId); } else { paging = new Paging(1, 500); } List<DirectMessage> dm = twitter.getDirectMessages(paging); List<DirectMessage> sent = twitter.getSentDirectMessages(paging); if (dm.size() != 0) { sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit(); numberNew = dm.size(); } else { numberNew = 0; } DMDataSource dataSource = DMDataSource.getInstance(context); int inserted = 0; for (DirectMessage directMessage : dm) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } inserted++; } for (DirectMessage directMessage : sent) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit(); if (settings.notifications && settings.dmsNot && inserted > 0) { int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0); sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit(); NotificationUtils.notifySecondDMs(context, currentAccount); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } }
From source file:com.esri.gpt.framework.security.identity.open.OpenidConsumerServlet.java
License:Apache License
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestContext context = null;/*from w ww. j a v a 2 s. c o m*/ boolean useFacade = false; String err = ""; try { LOGGER.finer("Query string=" + request.getQueryString()); String op = request.getParameter("op"); context = RequestContext.extract(request); OpenProviders providers = context.getIdentityConfiguration().getOpenProviders(); if ((providers == null) || (providers.size() == 0)) { return; } String baseContextPath = RequestContext.resolveBaseContextPath(request); String callbackUrl = baseContextPath + "/openid"; String realm = baseContextPath; HttpSession session = request.getSession(); // process a response from an Openid provider if (op == null) { String identity = null; String username = null; String email = null; // determine the callback info String cbinfo = Val.chkStr((String) session.getAttribute(ATTR_CBINFO)); session.setAttribute(ATTR_CBINFO, null); if (cbinfo.length() == 0) { throw new ServletException("Invalid openid callback info."); } int idx = cbinfo.indexOf(","); long millis = Long.parseLong(cbinfo.substring(0, idx)); cbinfo = cbinfo.substring(idx + 1); idx = cbinfo.indexOf(","); String cbid = cbinfo.substring(0, idx); cbinfo = cbinfo.substring(idx + 1); idx = cbinfo.indexOf(","); op = cbinfo.substring(0, idx); String fwd = cbinfo.substring(idx + 1); LOGGER.finer("cbinfo retrieved: " + cbinfo); // determine the provider OpenProvider provider = providers.get(op); if (provider == null) { throw new ServletException("Invalid openid op parameter on callback: " + op); } boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter"); // determine the authenticated user attributes if (useFacade) { identity = "http://openidfacade/user123"; email = "user123@openidfacade.com"; username = email; // Twitter callback } else if (isTwitter) { try { LOGGER.finer("Determining user attributes for: " + op); String token = (String) session.getAttribute(ATTR_TOKEN); String tokenSecret = (String) session.getAttribute(ATTR_TOKEN_SECRET); Twitter twitter = new Twitter(); twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret()); AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret); twitter.setOAuthAccessToken(accessToken); twitter4j.User tUser = twitter.verifyCredentials(); String screenName = Val.chkStr(tUser.getScreenName()); if (screenName.length() > 0) { username = screenName + "@twitter"; identity = "twitter:" + screenName; } } catch (Exception e) { err = "oAuth authentication failed."; LOGGER.log(Level.WARNING, err, e); } // Openid callback } else { try { // determine the callback UUID String cbidParam = Val.chkStr(request.getParameter("cbid")); if (cbidParam.length() == 0) { throw new ServletException("Empty cbid parameter on callback."); } if (!cbid.equals(cbidParam)) { throw new ServletException("Invalid openid cbid parameter on callback."); } callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8"); LOGGER.finer("cbinfo based callback: " + cbinfo); LOGGER.finer("Determining user attributes for: " + op); OpenIdManager manager = new OpenIdManager(); manager.setRealm(realm); manager.setReturnTo(callbackUrl); checkNonce(request.getParameter("openid.response_nonce")); byte[] mac_key = (byte[]) session.getAttribute(ATTR_MAC); String alias = (String) session.getAttribute(ATTR_ALIAS); Authentication authentication = manager.getAuthentication(request, mac_key, alias); identity = authentication.getIdentity(); email = authentication.getEmail(); username = email; } catch (Exception e) { err = "Openid authentication suceeded, creating local user reference failed."; LOGGER.log(Level.WARNING, err, e); } } // check the parameters identity = Val.chkStr(identity); username = Val.chkStr(username); email = Val.chkStr(email); LOGGER.finer( "User attributes: identity=" + identity + ", username=" + username + ", email=" + email); if (identity.length() == 0) { err = "Your openid idenitfier was not determined."; } else if (username.length() == 0) { if (isTwitter) { err = "Your opennid screen name was not determined."; } else { err = "Your opennid email address was not determined."; } } else { // establish the user identity = "urn:openid:" + identity; User user = context.getUser(); user.reset(); user.setKey(identity); user.setDistinguishedName(identity); user.setName(username); user.getProfile().setUsername(username); if (email.length() > 0) { user.getProfile().setEmailAddress(email); } user.getAuthenticationStatus().setWasAuthenticated(true); // ensure a local reference for the user try { LocalDao localDao = new LocalDao(context); localDao.ensureReferenceToRemoteUser(user); } catch (Exception e) { user.reset(); err = "Openid authentication suceeded, creating local user reference failed."; LOGGER.log(Level.SEVERE, err, e); } } // redirect to the originating page String url = fwd; err = Val.chkStr(err); if (err.length() > 0) { if (url.indexOf("?") == -1) fwd += "?"; else url += "&"; url += "err=" + URLEncoder.encode(err, "UTF-8"); } response.sendRedirect(url); // process a request to enter Openid credentials } else if (op.length() > 0) { session.setAttribute(ATTR_CBINFO, null); // determine the provider OpenProvider provider = providers.get(op); if (provider == null) { throw new ServletException("Invalid openid op parameter: " + op); } boolean isTwitter = provider.getName().equalsIgnoreCase("Twitter"); // determine the active Geoportal page (forward URL) String fwd = Val.chkStr(request.getParameter("fwd")); if (fwd.length() == 0) { throw new ServletException("Empty openid fwd parameter."); } // store the callback info String cbid = UUID.randomUUID().toString(); long millis = System.currentTimeMillis(); String cbinfo = millis + "," + cbid + "," + op + "," + fwd; session.setAttribute(ATTR_CBINFO, cbinfo); // determine the Openid Authentication URL String url = null; if (useFacade) { PrintWriter pw = response.getWriter(); pw.println("<html><head><title>Openid Facade</title></head><body><h1>Openid Facade</h1>"); pw.println("<a href=\"" + callbackUrl + "\">Supply credentials step</a>"); pw.println("</body></html>"); pw.flush(); return; // Twitter } else if (isTwitter) { try { LOGGER.fine("Initiating oAuth request for: " + op + ", callback=" + callbackUrl); Twitter twitter = new Twitter(); twitter.setOAuthConsumer(provider.getConsumerKey(), provider.getConsumerSecret()); RequestToken requestToken = twitter.getOAuthRequestToken(); String token = requestToken.getToken(); String tokenSecret = requestToken.getTokenSecret(); session.setAttribute(ATTR_TOKEN, token); session.setAttribute(ATTR_TOKEN_SECRET, tokenSecret); url = requestToken.getAuthorizationURL(); } catch (TwitterException e) { err = "Unable to determine endpoint for: " + op; LOGGER.log(Level.SEVERE, err, e); } // Openid } else { try { callbackUrl += "?cbid=" + java.net.URLEncoder.encode(cbid, "UTF-8"); LOGGER.finer("Initiating openid request for: " + op + ", callback=" + callbackUrl); OpenIdManager manager = new OpenIdManager(); manager.setRealm(realm); manager.setReturnTo(callbackUrl); // There is an issue here. It seems that the only way to set the endpoint // alias is through the jopenid-1.07.jar openid-providers.properties, // but we would to to configure the provider properties through gpt.xml //Endpoint endpoint = manager.lookupEndpoint(provider.getAuthenticationUrl()); Endpoint endpoint = manager.lookupEndpoint(op); Association association = manager.lookupAssociation(endpoint); request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey()); request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias()); url = manager.getAuthenticationUrl(endpoint, association); } catch (Exception e) { err = "Unable to determine Openid endpoint for: " + op; LOGGER.log(Level.SEVERE, err, e); } } // redirect to the authentication endpoint or to originating page err = Val.chkStr(err); if (err.length() > 0) { url = fwd; if (url.indexOf("?") == -1) fwd += "?"; else url += "&"; url += "err=" + URLEncoder.encode(err, "UTF-8"); } LOGGER.finer("Redirecting for authentication: " + url); response.sendRedirect(url); } else { throw new ServletException("Empty openid op parameter."); } } finally { if (context != null) context.onExecutionPhaseCompleted(); } }
From source file:com.freedomotic.plugins.devices.twitter.gateways.OAuthSetup.java
License:Open Source License
/** * @param args// w ww .ja va 2 s . c o m */ public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); //insert the appropriate consumer key and consumer secret here twitter.setOAuthConsumer("TLGtvoeABqf2tEG4itTUaw", "nUJPxYR1qJmhX9SnWTBT0MzO7dIqUtNyVPfhg10wf0"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } //persist to the accessToken for future reference. System.out.println(twitter.verifyCredentials().getId()); System.out.println("token : " + accessToken.getToken()); System.out.println("tokenSecret : " + accessToken.getTokenSecret()); //storeAccessToken(twitter.verifyCredentials().getId() , accessToken); Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); }
From source file:com.ikungolf.java.javatwitter.GetHomeTimeline.java
License:Apache License
/** * Usage: java twitter4j.examples.timeline.GetHomeTimeline * * @param args String[]/*from w w w .ja va 2 s .com*/ */ public static void main(String[] args) { try { // gets Twitter instance with default credentials Twitter twitter = new TwitterFactory().getInstance(); User user = twitter.verifyCredentials(); List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing @" + user.getScreenName() + "'s home timeline."); for (Status status : statuses) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } }
From source file:com.ikungolf.java.javatwitter.GetMentions.java
License:Apache License
/** * Usage: java twitter4j.examples.timeline.GetMentions * * @param args String[]//from w w w .j a v a 2 s.co m */ public static void main(String[] args) { // gets Twitter instance with default credentials Twitter twitter = new TwitterFactory().getInstance(); try { User user = twitter.verifyCredentials(); List<Status> statuses = twitter.getMentionsTimeline(); System.out.println("Showing @" + user.getScreenName() + "'s mentions."); for (Status status : statuses) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } }
From source file:com.ikungolf.java.javatwitter.twitterCmd.java
public Status getLastestMessage() { String msg = new String(); Status s = null;//w w w.jav a2 s . c o m // gets Twitter instance with default credentials Twitter twitter = new TwitterFactory().getInstance(); try { User user = twitter.verifyCredentials(); List<Status> statuses = twitter.getMentionsTimeline(); s = statuses.get(0); msg = s.getText(); System.out.println("Message: " + s.getText()); // for (Status status : statuses) { // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); // } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } return s; }
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 w ww . j a v a 2 s . co m } 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.DirectMessageRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); 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;/*from w w w. j ava 2s . c o m*/ } boolean update = false; int numberNew = 0; try { Twitter twitter = Utils.getTwitter(context, settings); int currentAccount = sharedPrefs.getInt("current_account", 1); User user = twitter.verifyCredentials(); long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0); Paging paging; if (lastId != 0) { paging = new Paging(1).sinceId(lastId); } else { paging = new Paging(1, 500); } List<DirectMessage> dm = twitter.getDirectMessages(paging); List<DirectMessage> sent = twitter.getSentDirectMessages(paging); if (dm.size() != 0) { sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit(); numberNew = dm.size(); } else { numberNew = 0; } DMDataSource dataSource = DMDataSource.getInstance(context); int inserted = 0; for (DirectMessage directMessage : dm) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } inserted++; } for (DirectMessage directMessage : sent) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit(); if (settings.notifications && settings.dmsNot && inserted > 0) { int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0); sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit(); NotificationUtils.refreshNotification(context); } if (settings.syncSecondMentions) { startService(new Intent(context, SecondDMRefreshService.class)); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } }
From source file:com.klinker.android.twitter.services.SecondDMRefreshService.java
License:Apache License
@Override public void onHandleIntent(Intent intent) { sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); 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;//w w w. j a va 2s. c o m } boolean update = false; int numberNew = 0; try { Twitter twitter = Utils.getSecondTwitter(context); int currentAccount = sharedPrefs.getInt("current_account", 1); if (currentAccount == 1) { currentAccount = 2; } else { currentAccount = 1; } User user = twitter.verifyCredentials(); long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0); Paging paging; if (lastId != 0) { paging = new Paging(1).sinceId(lastId); } else { paging = new Paging(1, 500); } List<DirectMessage> dm = twitter.getDirectMessages(paging); List<DirectMessage> sent = twitter.getSentDirectMessages(paging); if (dm.size() != 0) { sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit(); numberNew = dm.size(); } else { numberNew = 0; } DMDataSource dataSource = DMDataSource.getInstance(context); int inserted = 0; for (DirectMessage directMessage : dm) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } inserted++; } for (DirectMessage directMessage : sent) { try { dataSource.createDirectMessage(directMessage, currentAccount); } catch (Exception e) { dataSource = DMDataSource.getInstance(context); dataSource.createDirectMessage(directMessage, currentAccount); } } sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit(); if (settings.notifications && settings.dmsNot && inserted > 0) { int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0); sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit(); NotificationUtils.notifySecondDMs(context, currentAccount); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } }