Search in sources :

Example 11 with AppSettings

use of com.klinker.android.twitter.settings.AppSettings in project Talon-for-Twitter by klinker24.

the class TweetWearableService method onMessageReceived.

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    final WearableUtils wearableUtils = new WearableUtils();
    final BitmapLruCache cache = App.getInstance(this).getBitmapCache();
    if (markReadHandler == null) {
        markReadHandler = new Handler();
    }
    final String message = new String(messageEvent.getData());
    Log.d(TAG, "got message: " + message);
    final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
    ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "Failed to connect to GoogleApiClient.");
        return;
    }
    if (message.equals(KeyProperties.GET_DATA_MESSAGE)) {
        AppSettings settings = AppSettings.getInstance(this);
        Cursor tweets = HomeDataSource.getInstance(this).getWearCursor(settings.currentAccount);
        PutDataMapRequest dataMap = PutDataMapRequest.create(KeyProperties.PATH);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> screennames = new ArrayList<String>();
        ArrayList<String> bodies = new ArrayList<String>();
        ArrayList<String> ids = new ArrayList<String>();
        if (tweets != null && tweets.moveToLast()) {
            do {
                String name = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_NAME));
                String screenname = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_SCREEN_NAME));
                String pic = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_PRO_PIC));
                String body = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TEXT));
                long id = tweets.getLong(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID));
                String retweeter;
                try {
                    retweeter = tweets.getString(tweets.getColumnIndex(HomeSQLiteHelper.COLUMN_RETWEETER));
                } catch (Exception e) {
                    retweeter = "";
                }
                screennames.add(screenname);
                names.add(name);
                if (TextUtils.isEmpty(retweeter)) {
                    body = pic + KeyProperties.DIVIDER + body + KeyProperties.DIVIDER;
                } else {
                    body = pic + KeyProperties.DIVIDER + body + "<br><br>" + getString(R.string.retweeter) + retweeter + KeyProperties.DIVIDER;
                }
                bodies.add(Html.fromHtml(body.replace("<p>", KeyProperties.LINE_BREAK)).toString());
                ids.add(id + "");
            } while (tweets.moveToPrevious() && tweets.getCount() - tweets.getPosition() < MAX_ARTICLES_TO_SYNC);
            tweets.close();
        }
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_NAME, names);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_USER_SCREENNAME, screennames);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_TWEET, bodies);
        dataMap.getDataMap().putStringArrayList(KeyProperties.KEY_ID, ids);
        // light background with orange accent or theme color accent
        dataMap.getDataMap().putInt(KeyProperties.KEY_PRIMARY_COLOR, Color.parseColor("#dddddd"));
        if (settings.addonTheme) {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR, settings.accentInt);
        } else {
            dataMap.getDataMap().putInt(KeyProperties.KEY_ACCENT_COLOR, getResources().getColor(R.color.orange_primary_color));
        }
        dataMap.getDataMap().putLong(KeyProperties.KEY_DATE, System.currentTimeMillis());
        for (String node : wearableUtils.getNodes(googleApiClient)) {
            byte[] bytes = dataMap.asPutDataRequest().getData();
            Wearable.MessageApi.sendMessage(googleApiClient, node, KeyProperties.PATH, bytes);
            Log.v(TAG, "sent " + bytes.length + " bytes of data to node " + node);
        }
    } else if (message.startsWith(KeyProperties.MARK_READ_MESSAGE)) {
        markReadHandler.removeCallbacksAndMessages(null);
        markReadHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                String[] messageContent = message.split(KeyProperties.DIVIDER);
                final long id = Long.parseLong(messageContent[1]);
                final AppSettings settings = AppSettings.getInstance(TweetWearableService.this);
                try {
                    HomeDataSource.getInstance(TweetWearableService.this).markPosition(settings.currentAccount, id);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
                sendBroadcast(new Intent("com.klinker.android.twitter.CLEAR_PULL_UNREAD"));
                final SharedPreferences sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
                // mark tweetmarker if they use it
                if (AppSettings.getInstance(TweetWearableService.this).tweetmarker) {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            TweetMarkerHelper helper = new TweetMarkerHelper(settings.currentAccount, sharedPrefs.getString("twitter_screen_name_" + settings.currentAccount, ""), Utils.getTwitter(TweetWearableService.this, settings), sharedPrefs);
                            helper.sendCurrentId("timeline", id);
                            startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                        }
                    }).start();
                } else {
                    startService(new Intent(TweetWearableService.this, HandleScrollService.class));
                }
            }
        }, 5000);
    } else if (message.startsWith(KeyProperties.REQUEST_FAVORITE)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).createFavorite(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_COMPOSE)) {
        final String status = message.split(KeyProperties.DIVIDER)[1];
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_RETWEET)) {
        final long tweetId = Long.parseLong(message.split(KeyProperties.DIVIDER)[1]);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).retweetStatus(tweetId);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_REPLY)) {
        final String tweet = message.split(KeyProperties.DIVIDER)[1];
        final long replyToId = Long.parseLong(message.split(KeyProperties.DIVIDER)[2]);
        final StatusUpdate status = new StatusUpdate(tweet);
        status.setInReplyToStatusId(replyToId);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Utils.getTwitter(TweetWearableService.this, AppSettings.getInstance(TweetWearableService.this)).updateStatus(status);
                } catch (Exception e) {
                }
            }
        }).start();
    } else if (message.startsWith(KeyProperties.REQUEST_IMAGE)) {
        final String url = message.split(KeyProperties.DIVIDER)[1];
        Bitmap image = null;
        try {
            cache.get(url).getBitmap();
        } catch (Exception e) {
        }
        if (image != null) {
            image = adjustImage(image);
            sendImage(image, url, wearableUtils, googleApiClient);
        } else {
            // download it
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        InputStream is = new BufferedInputStream(conn.getInputStream());
                        Bitmap image = decodeSampledBitmapFromResourceMemOpt(is, 500, 500);
                        try {
                            is.close();
                        } catch (Exception e) {
                        }
                        try {
                            conn.disconnect();
                        } catch (Exception e) {
                        }
                        cache.put(url, image);
                        image = adjustImage(image);
                        sendImage(image, url, wearableUtils, googleApiClient);
                    } catch (Exception e) {
                    }
                }
            }).start();
        }
    } else {
        Log.e(TAG, "message not recognized");
    }
}
Also used : WearableUtils(com.klinker.android.twitter.utils.WearableUtils) AppSettings(com.klinker.android.twitter.settings.AppSettings) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) URL(java.net.URL) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) PutDataMapRequest(com.google.android.gms.wearable.PutDataMapRequest) GoogleApiClient(com.google.android.gms.common.api.GoogleApiClient) SharedPreferences(android.content.SharedPreferences) TweetMarkerHelper(com.klinker.android.twitter.utils.api_helper.TweetMarkerHelper) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Handler(android.os.Handler) Intent(android.content.Intent) StatusUpdate(twitter4j.StatusUpdate) BitmapLruCache(uk.co.senab.bitmapcache.BitmapLruCache) HandleScrollService(com.klinker.android.twitter.activities.launcher_page.HandleScrollService) ConnectionResult(com.google.android.gms.common.ConnectionResult)

Example 12 with AppSettings

use of com.klinker.android.twitter.settings.AppSettings in project Talon-for-Twitter by klinker24.

the class BootReceiver method onReceive.

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    AppSettings settings = AppSettings.getInstance(context);
    if (settings.timelineRefresh != 0) {
        // user only wants manual
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = new Date().getTime();
        long alarm = now + settings.timelineRefresh;
        Log.v("alarm_date", "timeline " + new Date(alarm).toString());
        PendingIntent pendingIntent = PendingIntent.getService(context, HomeFragment.HOME_REFRESH_ID, new Intent(context, TimelineRefreshService.class), 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.timelineRefresh, pendingIntent);
    }
    if (settings.mentionsRefresh != 0) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = new Date().getTime();
        long alarm = now + settings.mentionsRefresh;
        Log.v("alarm_date", "mentions " + new Date(alarm).toString());
        PendingIntent pendingIntent = PendingIntent.getService(context, MentionsFragment.MENTIONS_REFRESH_ID, new Intent(context, MentionsRefreshService.class), 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.mentionsRefresh, pendingIntent);
    }
    if (settings.dmRefresh != 0) {
        // user only wants manual
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = new Date().getTime();
        long alarm = now + settings.dmRefresh;
        Log.v("alarm_date", "dircet message " + new Date(alarm).toString());
        PendingIntent pendingIntent = PendingIntent.getService(context, DMFragment.DM_REFRESH_ID, new Intent(context, DirectMessageRefreshService.class), 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.dmRefresh, pendingIntent);
    }
    if (settings.activityRefresh != 0) {
        // user only wants manual
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = new Date().getTime();
        long alarm = now + settings.activityRefresh;
        Log.v("alarm_date", "activity " + new Date(alarm).toString());
        PendingIntent pendingIntent = PendingIntent.getService(context, ActivityFragment.ACTIVITY_REFRESH_ID, new Intent(context, ActivityRefreshService.class), 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.activityRefresh, pendingIntent);
    }
    if (settings.autoTrim) {
        // user only wants manual
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = new Date().getTime();
        long alarm = now + 1000 * 60;
        Log.v("alarm_date", "auto trim " + new Date(alarm).toString());
        PendingIntent pendingIntent = PendingIntent.getService(context, TRIM_ID, new Intent(context, TrimDataService.class), 0);
        am.set(AlarmManager.RTC_WAKEUP, alarm, pendingIntent);
    }
    if (settings.pushNotifications) {
        context.startService(new Intent(context, CatchupPull.class));
    }
    ArrayList<ScheduledTweet> tweets = QueuedDataSource.getInstance(context).getScheduledTweets();
    for (ScheduledTweet s : tweets) {
        Intent serviceIntent = new Intent(context.getApplicationContext(), SendScheduledTweet.class);
        Log.v("talon_scheduled_tweets", "in boot text: " + s.text);
        serviceIntent.putExtra(ViewScheduledTweets.EXTRA_TEXT, s.text);
        serviceIntent.putExtra("account", s.account);
        serviceIntent.putExtra("alarm_id", s.alarmId);
        PendingIntent pi = getDistinctPendingIntent(serviceIntent, s.alarmId);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, s.time, pi);
    }
}
Also used : AppSettings(com.klinker.android.twitter.settings.AppSettings) ScheduledTweet(com.klinker.android.twitter.data.ScheduledTweet) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Date(java.util.Date) AlarmManager(android.app.AlarmManager) PendingIntent(android.app.PendingIntent)

Example 13 with AppSettings

use of com.klinker.android.twitter.settings.AppSettings in project Talon-for-Twitter by klinker24.

the class ConnectivityChangeReceiver method onReceive.

@Override
public void onReceive(final Context context, final Intent intent) {
    Log.v("talon_pull", "connectivity change: just starting receiver");
    AppSettings settings = AppSettings.getInstance(context);
    // we don't want to do anything here if talon pull isn't on
    if (!settings.pushNotifications) {
        Log.v("talon_pull", "connectivity change: stopping the receiver very early");
        return;
    }
    if (Utils.hasInternetConnection(context)) {
        Log.v("talon_pull", "connectivity change: network is available and talon pull is on");
        // we want to turn off the live streaming/talon pull because it is just wasting battery not working/looking for connection
        context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE"));
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = Calendar.getInstance().getTimeInMillis();
        // schedule it to begin in 1 min
        long alarm = now + 60000;
        PendingIntent pendingIntent = PendingIntent.getService(context, 236, new Intent(context, CatchupPull.class), 0);
        // cancel the old one, then start the new one in 1 min
        am.cancel(pendingIntent);
        am.set(AlarmManager.RTC_WAKEUP, alarm, pendingIntent);
    } else {
        Log.v("talon_pull", "connectivity change: network not available but talon pull is on");
        // we want to turn off the live streaming/talon pull because it is just wasting battery not working/looking for connection
        context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE"));
    }
}
Also used : AppSettings(com.klinker.android.twitter.settings.AppSettings) AlarmManager(android.app.AlarmManager) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) CatchupPull(com.klinker.android.twitter.services.CatchupPull)

Example 14 with AppSettings

use of com.klinker.android.twitter.settings.AppSettings in project Talon-for-Twitter by klinker24.

the class QueueTweets method onReceive.

@Override
public void onReceive(final Context context, final Intent intent) {
    Log.v("talon_queued", "connectivity change: just starting receiver");
    AppSettings settings = AppSettings.getInstance(context);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    long now = Calendar.getInstance().getTimeInMillis();
    // schedule it to begin in 20 seconds
    long alarm = now + 10000;
    PendingIntent pendingIntent = PendingIntent.getService(context, 253, new Intent(context, SendQueue.class), 0);
    // cancel the old one, then start the new one in 1 min
    am.cancel(pendingIntent);
    if (Utils.hasInternetConnection(context) && QueuedDataSource.getInstance(context).getQueuedTweets(settings.currentAccount).length > 0) {
        Log.v("talon_queued", "setting alarm for queue");
        am.set(AlarmManager.RTC_WAKEUP, alarm, pendingIntent);
    }
}
Also used : AppSettings(com.klinker.android.twitter.settings.AppSettings) AlarmManager(android.app.AlarmManager) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) SendQueue(com.klinker.android.twitter.services.SendQueue)

Example 15 with AppSettings

use of com.klinker.android.twitter.settings.AppSettings in project Talon-for-Twitter by klinker24.

the class SecondDMRefreshService method onHandleIntent.

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
    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;
    }
    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());
    }
}
Also used : Context(android.content.Context) AppSettings(com.klinker.android.twitter.settings.AppSettings) DMDataSource(com.klinker.android.twitter.data.sq_lite.DMDataSource)

Aggregations

AppSettings (com.klinker.android.twitter.settings.AppSettings)33 Intent (android.content.Intent)18 PendingIntent (android.app.PendingIntent)10 Context (android.content.Context)10 NotificationCompat (android.support.v4.app.NotificationCompat)9 SharedPreferences (android.content.SharedPreferences)6 Cursor (android.database.Cursor)6 Bitmap (android.graphics.Bitmap)6 PowerManager (android.os.PowerManager)6 NotificationManagerCompat (android.support.v4.app.NotificationManagerCompat)6 Paging (twitter4j.Paging)6 ArrayList (java.util.ArrayList)5 Twitter (twitter4j.Twitter)5 HomeDataSource (com.klinker.android.twitter.data.sq_lite.HomeDataSource)4 MentionsDataSource (com.klinker.android.twitter.data.sq_lite.MentionsDataSource)4 Status (twitter4j.Status)4 AlarmManager (android.app.AlarmManager)3 Handler (android.os.Handler)3 RemoteInput (android.support.v4.app.RemoteInput)3 DMDataSource (com.klinker.android.twitter.data.sq_lite.DMDataSource)3