Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

In this page you can find the example usage for android.app PendingIntent getService.

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void refreshNotification(Context context, boolean noTimeline) {
    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences(
            "com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    int currentAccount = sharedPrefs.getInt("current_account", 1);

    //int[] unreadCounts = new int[] {4, 1, 2}; // for testing
    int[] unreadCounts = getUnreads(context);

    int timeline = unreadCounts[0];
    int realTimelineCount = timeline;

    // if they don't want that type of notification, simply set it to zero
    if (!settings.timelineNot || (settings.pushNotifications && settings.liveStreaming) || noTimeline) {
        unreadCounts[0] = 0;/*  www  .  jav a2s  . c  om*/
    }
    if (!settings.mentionsNot) {
        unreadCounts[1] = 0;
    }
    if (!settings.dmsNot) {
        unreadCounts[2] = 0;
    }

    if (unreadCounts[0] == 0 && unreadCounts[1] == 0 && unreadCounts[2] == 0) {

    } else {
        Intent markRead = new Intent(context, MarkReadService.class);
        PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

        String shortText = getShortText(unreadCounts, context, currentAccount);
        String longText = getLongText(unreadCounts, context, currentAccount);
        // [0] is the full title and [1] is the screenname
        String[] title = getTitle(unreadCounts, context, currentAccount);
        boolean useExpanded = useExp(context);
        boolean addButton = addBtn(unreadCounts);

        if (title == null) {
            return;
        }

        Intent resultIntent;

        if (unreadCounts[1] != 0 && unreadCounts[0] == 0) {
            // it is a mention notification (could also have a direct message)
            resultIntent = new Intent(context, RedirectToMentions.class);
        } else if (unreadCounts[2] != 0 && unreadCounts[0] == 0 && unreadCounts[1] == 0) {
            // it is a direct message
            resultIntent = new Intent(context, RedirectToDMs.class);
        } else {
            resultIntent = new Intent(context, MainActivity.class);
        }

        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

        NotificationCompat.Builder mBuilder;

        Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

        mBuilder = new NotificationCompat.Builder(context).setContentTitle(title[0])
                .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(getIcon(context, unreadCounts, title[1]))
                .setContentIntent(resultPendingIntent).setAutoCancel(true)
                .setTicker(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        if (unreadCounts[1] > 1 && unreadCounts[0] == 0 && unreadCounts[2] == 0) {
            // inbox style notification for mentions
            mBuilder.setStyle(getMentionsInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else if (unreadCounts[2] > 1 && unreadCounts[0] == 0 && unreadCounts[1] == 0) {
            // inbox style notification for direct messages
            mBuilder.setStyle(getDMInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else {
            // big text style for an unread count on timeline, mentions, and direct messages
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                    settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title[0], shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title[0], shortText);

        int homeTweets = unreadCounts[0];
        int mentionsTweets = unreadCounts[1];
        int dmTweets = unreadCounts[2];

        int newC = 0;

        if (homeTweets > 0) {
            newC++;
        }
        if (mentionsTweets > 0) {
            newC++;
        }
        if (dmTweets > 0) {
            newC++;
        }

        if (settings.notifications && newC > 0) {

            if (settings.vibrate) {
                mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            }

            if (settings.sound) {
                try {
                    mBuilder.setSound(Uri.parse(settings.ringtone));
                } catch (Exception e) {
                    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                }
            }

            if (settings.led)
                mBuilder.setLights(0xFFFFFF, 1000, 1000);

            // Get an instance of the NotificationManager service
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            if (addButton) { // the reply and read button should be shown
                Intent reply;
                if (unreadCounts[1] == 1) {
                    reply = new Intent(context, NotificationCompose.class);
                } else {
                    reply = new Intent(context, NotificationDMCompose.class);
                }

                Log.v("username_for_noti", title[1]);
                sharedPrefs.edit().putString("from_notification", "@" + title[1] + " " + title[2]).commit();
                MentionsDataSource data = MentionsDataSource.getInstance(context);
                long id = data.getLastIds(currentAccount)[0];
                PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);
                sharedPrefs.edit().putLong("from_notification_long", id).commit();
                sharedPrefs.edit()
                        .putString("from_notification_text",
                                "@" + title[1] + ": " + TweetLinkUtils.removeColorHtml(shortText, settings))
                        .commit();

                // Create the remote input
                RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                        .setLabel("@" + title[1] + " ").build();

                // Create the notification action
                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
                        replyPending).addRemoteInput(remoteInput).build();

                NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read),
                        readPending);

                mBuilder.addAction(replyAction);
                mBuilder.addAction(action.build());
            } else { // otherwise, if they can use the expanded notifications, the popup button will be shown
                Intent popup = new Intent(context, RedirectToPopup.class);
                popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                popup.putExtra("from_notification", true);

                PendingIntent popupPending = PendingIntent.getActivity(context, 0, popup, 0);

                NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
                        R.drawable.ic_popup, context.getResources().getString(R.string.popup), popupPending);

                mBuilder.addAction(action.build());
            }

            // Build the notification and issues it with notification manager.
            notificationManager.notify(1, mBuilder.build());

            // if we want to wake the screen on a new message
            if (settings.wakeScreen) {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                        | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
                wakeLock.acquire(5000);
            }
        }

        // if there are unread tweets on the timeline, check them for favorite users
        if (settings.favoriteUserNotifications && realTimelineCount > 0) {
            favUsersNotification(currentAccount, context);
        }
    }

    try {

        ContentValues cv = new ContentValues();

        cv.put("tag", "com.klinker.android.twitter/com.klinker.android.twitter.ui.MainActivity");

        // add the direct messages and mentions
        cv.put("count", unreadCounts[1] + unreadCounts[2]);

        context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);

    } catch (IllegalArgumentException ex) {

        /* Fine, TeslaUnread is not installed. */

    } catch (Exception ex) {

        /* Some other error, possibly because the format
           of the ContentValues are incorrect.
                
        Log but do not crash over this. */

        ex.printStackTrace();

    }
}

From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java

private void cancelAlarm(final long matchId, final long matchStart) {
    final long currentTime = TimeUtils.getUTCTime();

    LOGD(TAG, "Unscheduling Alarm");

    if (currentTime > matchStart) {
        LOGD(TAG, "wat.");
        return;// w w w. j  a va2 s  . co m
    }

    final Intent notifIntent = new Intent(ACTION_NOTIFY_MATCH, null, this, ReminderAlarmService.class);

    notifIntent.setData(
            new Uri.Builder().authority("ca.zadrox.dota2esportticker").path(String.valueOf(matchId)).build());

    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_ID, matchId);
    notifIntent.putExtra(ReminderAlarmService.EXTRA_MATCH_START, matchStart);

    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);

    am.cancel(pi);
}

From source file:com.bangalore.barcamp.BCBUtils.java

public static PendingIntent createPendingIntentForID(Context context, String id, int slot, int session) {
    Intent intent = new Intent(context, SessionAlarmIntentService.class);
    intent.putExtra(SessionAlarmIntentService.SESSION_ID, id);
    intent.putExtra(SessionAlarmIntentService.EXTRA_SLOT_POS, slot);
    intent.putExtra(SessionAlarmIntentService.EXTRA_SESSION_POSITION, session);
    int idInt = Integer.parseInt(id);
    PendingIntent pendingIntent = PendingIntent.getService(context, idInt, intent, PendingIntent.FLAG_ONE_SHOT);
    return pendingIntent;
}

From source file:com.readystatesoftware.chuck.internal.support.NotificationHelper.java

@NonNull
private NotificationCompat.Action getClearAction() {
    CharSequence clearTitle = context.getString(R.string.chuck_clear);
    Intent deleteIntent = new Intent(context, ClearTransactionsService.class);
    PendingIntent intent = PendingIntent.getService(context, 11, deleteIntent, PendingIntent.FLAG_ONE_SHOT);
    return new NotificationCompat.Action(R.drawable.chuck_ic_delete_white_24dp, clearTitle, intent);
}

From source file:de.azapps.mirakel.sync.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//from ww  w  .java2s.  co m
    // Mostly it is annoying if there is a notification. So don't show it
    boolean showNotification = false;
    // But if the user actively clicks on "sync"  then show it.
    if (extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL))
        showNotification = true;

    Log.v(TAG, "SyncAdapter");
    Intent intent = new Intent(mContext, MainActivity.class);
    intent.setAction(MainActivity.SHOW_LISTS);
    PendingIntent p = PendingIntent.getService(mContext, 0, intent, 0);

    NotificationCompat.Builder mNB = new NotificationCompat.Builder(mContext).setContentTitle("Mirakel")
            .setContentText("Sync").setSmallIcon(android.R.drawable.stat_notify_sync)
            .setWhen(System.currentTimeMillis()).setOngoing(true).setContentIntent(p);
    if (showNotification)
        mNotificationManager.notify(notifyID, mNB.build());

    String type = (AccountManager.get(mContext)).getUserData(account, BUNDLE_SERVER_TYPE);
    boolean success = false;
    if (type == null)
        type = TaskWarriorSync.TYPE;
    if (type.equals(TaskWarriorSync.TYPE)) {
        TW_ERRORS error = new TaskWarriorSync(mContext).sync(account);
        switch (error) {
        case NO_ERROR:
            last_message = mContext.getText(R.string.finish_sync);
            success = true;
            break;
        case TRY_LATER:
            last_message = mContext.getText(R.string.message_try_later);
            break;
        case ACCESS_DENIED:
            last_message = mContext.getText(R.string.message_access_denied);
            break;
        case CANNOT_CREATE_SOCKET:
            last_message = mContext.getText(R.string.message_create_socket);
            break;
        case ACCOUNT_SUSPENDED:
            last_message = mContext.getText(R.string.message_account_suspended);
            break;
        case CANNOT_PARSE_MESSAGE:
            last_message = mContext.getText(R.string.message_parse_message);
            break;
        case MESSAGE_ERRORS:
            last_message = mContext.getText(R.string.message_message_error);
            break;
        case CONFIG_PARSE_ERROR:
            last_message = mContext.getText(R.string.wrong_config);
            break;
        case NOT_ENABLED:
        default:
            return;

        }
        Log.d(TAG, "finish Sync");
    } else if (type.equals(CalDavSync.TYPE)) {
        new CalDavSync(mContext).sync(account);
    } else {
        Log.wtf(TAG, "Unknown SyncType");
    }
    mNotificationManager.cancel(notifyID);
    if (showNotification && !success) {
        mNB = new NotificationCompat.Builder(mContext)
                .setContentTitle("Mirakel: " + mContext.getText(R.string.finish_sync))
                .setContentText(last_message).setSmallIcon(android.R.drawable.stat_notify_sync)
                .setPriority(NotificationCompat.PRIORITY_LOW).setContentIntent(p);
        mNotificationManager.notify(notifyID, mNB.build());
    }
    Intent i = new Intent(Mirakel.SYNC_FINISHED);
    mContext.sendBroadcast(i);
}

From source file:com.actinarium.rhythm.control.RhythmNotificationService.java

private void handleShowNotification(int notificationId) {
    Application application = getApplication();
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification;//from w  w  w . j  ava2s  . com

    // If the application is not the host - show error and return.
    if (!(application instanceof RhythmControl.Host)) {
        notification = makeCommonNotification(getString(R.string.arl_no_host_text))
                .setColor(NOTIFICATION_ERROR_COLOR).setContentTitle(getString(R.string.arl_no_host_title))
                .build();
        manager.notify(notificationId, notification);
        return;
    }

    RhythmControl control = ((RhythmControl.Host) application).getRhythmControl();
    RhythmGroup currentGroup = control.getCurrentNotificationGroup();

    // If there are no groups yet - show warning and return.
    if (currentGroup == null) {
        notification = makeCommonNotification(getString(R.string.arl_no_groups_text))
                .setColor(NOTIFICATION_ERROR_COLOR).setContentTitle(getString(R.string.arl_no_groups_title))
                .build();
        manager.notify(notificationId, notification);
        return;
    }

    // Now if everything is OK:
    Intent nextGroupAction = new Intent(this, RhythmNotificationService.class);
    nextGroupAction.setAction(ACTION_NEXT_GROUP);
    PendingIntent piNextGroupAction = PendingIntent.getService(this, 0, nextGroupAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent nextOverlayAction = new Intent(this, RhythmNotificationService.class);
    nextOverlayAction.setAction(ACTION_NEXT_OVERLAY);
    PendingIntent piNextOverlayAction = PendingIntent.getService(this, 0, nextOverlayAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent dismissAction = new Intent(this, RhythmNotificationService.class);
    dismissAction.setAction(ACTION_DISMISS_QUICK_CONTROL);
    PendingIntent piDismissAction = PendingIntent.getService(this, 0, dismissAction,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // todo: another action when notification is clicked (control activity will be added in v1.0)

    // Determine what to write in notification
    RhythmOverlay currentOverlay = currentGroup.getCurrentOverlay();
    String groupText = getString(R.string.arl_group, currentGroup.toString());
    String overlayText = currentOverlay == null ? getString(R.string.arl_no_overlay)
            : getString(R.string.arl_overlay, currentOverlay.toString());

    // Finally, build and display the notification
    notification = makeCommonNotification(overlayText).setColor(NOTIFICATION_ICON_COLOR)
            .setContentTitle(groupText).setDeleteIntent(piDismissAction)
            .addAction(new NotificationCompat.Action(R.drawable.arl_loop, getString(R.string.arl_next_group),
                    piNextGroupAction))
            .addAction(new NotificationCompat.Action(R.drawable.arl_loop, getString(R.string.arl_next_overlay),
                    piNextOverlayAction))
            .build();
    manager.notify(notificationId, notification);
}

From source file:com.perm.DoomPlay.DownloadNotifBuilder.java

public Notification createPaused() {
    Notification notification = new Notification();
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.notif_download);

    views.setProgressBar(R.id.progressDownload, 100, 0, false);
    views.setTextViewText(R.id.notifTitle, context.getResources().getString(R.string.paused));
    views.setTextViewText(R.id.notifArtist, track.getArtist() + "-" + track.getTitle());
    views.setImageViewResource(R.id.notifPause, R.drawable.widget_play);

    Intent intentClose = new Intent(PlayingService.actionClose);
    intentClose.putExtra("aid", track.getAid());
    intentClose.setComponent(new ComponentName(context, DownloadingService.class));

    Intent intentPause = new Intent(PlayingService.actionIconPlay);
    intentPause.putExtra("aid", track.getAid());
    intentPause.setComponent(new ComponentName(context, DownloadingService.class));

    views.setOnClickPendingIntent(R.id.notifClose,
            PendingIntent.getService(context, notificationId, intentClose, PendingIntent.FLAG_UPDATE_CURRENT));

    views.setOnClickPendingIntent(R.id.notifPause,
            PendingIntent.getService(context, notificationId, intentPause, PendingIntent.FLAG_UPDATE_CURRENT));

    notification.contentView = views;/*from   w w  w  .  j a v  a  2s.co  m*/
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.icon = R.drawable.download_icon;

    return notification;
}

From source file:com.asalfo.wiulgi.service.UtilityService.java

/**
 * Called when a location update is requested
 *//*w ww .j a  v a 2s.  c  om*/
private void requestLocationInternal() {
    Log.v(TAG, ACTION_REQUEST_LOCATION);

    if (!Utils.checkFineLocationPermission(this)) {
        return;
    }

    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(Constants.GOOGLE_API_CLIENT_TIMEOUT_S,
            TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {

        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);

        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }

        // Request new location
        LocationRequest mLocationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest,
                PendingIntent.getService(this, 0, locationUpdatedIntent, 0));

        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG, connectionResult.getErrorCode()));
    }
}

From source file:com.daiv.android.twitter.services.TestPullNotificationService.java

@Override
public void onCreate() {
    super.onCreate();

    if (TestPullNotificationService.isRunning) {
        stopSelf();/* w  w  w . j a v  a  2 s . com*/
        return;
    }

    TestPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    showNotification = sharedPreferences.getBoolean("show_pull_notification", true);
    pullUnread = sharedPreferences.getInt("pull_unread", 0);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.Test_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;

                ids = new ArrayList<Long>();
                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);
                ids.add(settings.myId);

                currCursor = -1;
                blockedIds = new ArrayList<Long>();
                do {
                    idObject = twitter.getBlocksIDs(currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        blockedIds.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);

                idsLoaded = true;

                if (showNotification)
                    startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.daiv.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TestPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TestPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:de.electricdynamite.pasty.GCMIntentService.java

@SuppressLint("NewApi")
@Override/*  w ww. ja  v a2  s.com*/
protected void onMessage(Context context, Intent intent) {
    if (prefs == null)
        this.prefs = new PastyPreferencesProvider(context);
    final Bundle extras = intent.getExtras();
    if (extras == null) {
        Log.i(TAG, "onMessage(): Empty intent received");
        return;
    }
    final String mItemId = extras.getString("itemId");
    final String mItemStr = extras.getString("item");
    final int mEventId = Integer.parseInt(extras.getString("eventId"));
    if (mItemId == null || mItemStr == null || mItemId == "" || mItemStr == "") {
        Log.i(TAG, "onMessage(): Invalid intent received");
        return;
    }
    if (LOCAL_LOG)
        Log.v(TAG, "onMessage(): Received message for event: " + mEventId);
    switch (mEventId) {
    case EVENT_ITEM_ADDED:
        final String lastItemId = prefs.getLastItem();
        if (mItemId.equals(lastItemId))
            return;
        if (client == null) {
            client = new PastyClient(prefs.getRESTBaseURL(), true);
            client.setUsername(prefs.getUsername());
            client.setPassword(prefs.getPassword());
        }

        final ClipboardItem mItem = new ClipboardItem(mItemId, mItemStr);
        final Boolean mPush = prefs.getPush();
        final Boolean mCopyToClipboard = prefs.getPushCopyToClipboard();
        final Boolean mNotify = prefs.getPushNotify();
        if (mPush == true) {
            if (mCopyToClipboard == true) {
                if (mItem.getText() != "") {
                    Intent resultIntent = new Intent(this, CopyService.class);
                    resultIntent.putExtra("de.electricdynamite.pasty.itemId", mItem.getId());
                    resultIntent.putExtra("de.electricdynamite.pasty.item", mItem.getText());
                    resultIntent.putExtra("de.electricdynamite.pasty.notify", mNotify);
                    startService(resultIntent);
                    resultIntent = null;
                }
            } else {
                if (mNotify == true) {
                    String contentText = String.format(getString(R.string.notification_event_add_text),
                            mItem.getText());
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_stat_pasty)
                            .setContentTitle(getString(R.string.notification_event_add_title))
                            .setContentText(contentText).setAutoCancel(Boolean.TRUE);
                    // Creates an explicit intent for an Activity in your app
                    Intent resultIntent = new Intent(this, CopyService.class);
                    resultIntent.putExtra("de.electricdynamite.pasty.itemId", mItem.getId());
                    resultIntent.putExtra("de.electricdynamite.pasty.item", mItem.getText());
                    resultIntent.putExtra("de.electricdynamite.pasty.notify", mNotify);
                    PendingIntent resultPendingIntent = PendingIntent.getService(context, 0, resultIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);
                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    // mId allows you to update the notification later on.
                    mNotificationManager.notify(PastySharedStatics.NOTIFICATION_ID, mBuilder.build());
                }
            }
            JSONArray clipboard = null;
            try {
                clipboard = client.getClipboard();
                cacheClipboard(clipboard);
            } catch (PastyException e) {
                if (LOCAL_LOG)
                    Log.v(TAG, "Could not get clipboard: " + e.getMessage());
            }

        }
        break;
    default:
        Log.i(TAG, "onMessage(): Unsupported event: " + mEventId);
        break;
    }
    /* TODO Make ClipboardFragment react to changes from GCMIntentService */
}