Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

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

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:ch.carteggio.provider.sync.NotificationService.java

private void updateUnreadNotification(boolean newMessage) {

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    CarteggioProviderHelper helper = new CarteggioProviderHelper(this);

    int unreadCount = helper.getUnreadCount();

    if (unreadCount == 0) {

        mNotificationManager.cancel(INCOMING_NOTIFICATION_ID);

    } else {//from  ww  w .  j a  v a 2  s.  co  m

        String quantityString = getResources().getQuantityString(R.plurals.notification_new_incoming_messages,
                unreadCount);

        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(String.format(quantityString, unreadCount))
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentText(getString(R.string.notification_text_new_messages));

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        notifyBuilder.setContentIntent(resultPendingIntent);

        if (newMessage) {

            Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);

            long pattern[] = { 1000, 500, 2000 };

            if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
                notifyBuilder.setSound(uri);
                notifyBuilder.setVibrate(pattern);
            } else if (manager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
                notifyBuilder.setVibrate(pattern);
            }
        }

        mNotificationManager.notify(INCOMING_NOTIFICATION_ID, notifyBuilder.build());

    }

}

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private void buildPushNotification(Context context, Intent intent, PushDataInfo dataInfo) {
    String title = dataInfo.getTitle();
    String body = dataInfo.getAlert();
    String message = dataInfo.getPushDataString();
    Builder builder = new Builder(context);
    builder.setAutoCancel(true);/*from  w w w  . j  a  v  a 2 s.c  o  m*/
    builder.setContentTitle(title); // 
    builder.setContentText(body); // 
    builder.setTicker(body); // ??

    String[] remindType = dataInfo.getRemindType();
    if (remindType != null) {
        if (remindType.length == 3) {
            builder.setDefaults(Notification.DEFAULT_ALL);
        } else {
            int defaults = 0;
            for (int i = 0; i < remindType.length; i++) {
                if ("sound".equalsIgnoreCase(remindType[i])) {
                    defaults = Notification.DEFAULT_SOUND;
                    continue;
                }
                if ("shake".equalsIgnoreCase(remindType[i])) {
                    defaults = defaults | Notification.DEFAULT_VIBRATE;
                    continue;
                }
                if ("breathe".equalsIgnoreCase(remindType[i])) {
                    defaults = defaults | Notification.DEFAULT_LIGHTS;
                    continue;
                }
            }
            builder.setDefaults(defaults);
        }
    }

    Resources res = context.getResources();
    int icon = res.getIdentifier("icon", "drawable", intent.getPackage());
    builder.setSmallIcon(icon);
    builder.setWhen(System.currentTimeMillis()); // 

    String iconUrl = dataInfo.getIconUrl();
    boolean isDefaultIcon = !TextUtils.isEmpty(iconUrl) && "default".equalsIgnoreCase(iconUrl);
    Bitmap bitmap = null;
    if (!isDefaultIcon) {
        bitmap = getIconBitmap(context, iconUrl);
    }
    String fontColor = dataInfo.getFontColor();
    RemoteViews remoteViews = null;
    if (!TextUtils.isEmpty(fontColor)) {
        int color = BUtility.parseColor(fontColor);
        int alphaColor = parseAlphaColor(fontColor);
        remoteViews = new RemoteViews(intent.getPackage(), EUExUtil.getResLayoutID("push_notification_view"));
        // Title
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_title"), title);
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_title"), color);
        // Body
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_body"), body);
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_body"), alphaColor);
        // LargeIcon
        if (bitmap != null) {
            remoteViews.setImageViewBitmap(EUExUtil.getResIdID("notification_largeIcon"), bitmap);
        } else {
            remoteViews.setImageViewResource(EUExUtil.getResIdID("notification_largeIcon"),
                    EUExUtil.getResDrawableID("icon"));
        }
        // Time
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        remoteViews.setTextViewText(EUExUtil.getResIdID("notification_time"),
                format.format(System.currentTimeMillis()));
        remoteViews.setTextColor(EUExUtil.getResIdID("notification_time"), alphaColor);
        builder.setContent(remoteViews);
    }

    Intent notiIntent = new Intent(context, EBrowserActivity.class);
    notiIntent.putExtra("ntype", F_TYPE_PUSH);
    notiIntent.putExtra("data", body);
    notiIntent.putExtra("message", message);
    Bundle bundle = new Bundle();
    bundle.putSerializable(PushReportConstants.PUSH_DATA_INFO_KEY, dataInfo);
    notiIntent.putExtras(bundle);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationNB, notiIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = builder.build();
    // Android v4bug2.3?Builder?NotificationRemoteView??
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && remoteViews != null) {
        notification.contentView = remoteViews;
    }
    manager.notify(notificationNB, notification);
    notificationNB++;
}

From source file:com.onesignal.GenerateNotification.java

private static PendingIntent getNewActionPendingIntent(int requestCode, Intent intent) {
    if (openerIsBroadcast)
        return PendingIntent.getBroadcast(currentContext, requestCode, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    return PendingIntent.getActivity(currentContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

private void notify(Context context, boolean isConnectedPower, boolean hasVibration, boolean hasSound,
        int notifyCount) {
    final Resources res = context.getResources();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentTitle(res.getString(R.string.notify_content_title))
            .setAutoCancel(true);//from w  ww .  j ava  2  s .  c  om

    if (notifyCount == 1) {
        final int resContentTextSingle = (isConnectedPower ? R.string.notify_content_text_single_on
                : R.string.notify_content_text_single_off);
        mBuilder.setContentText(res.getString(resContentTextSingle));
    } else {
        mBuilder.setNumber(notifyCount).setContentText(res.getString(R.string.notify_content_text_multi));
    }

    if (hasVibration && hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
    } else if (hasVibration) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    } else if (hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    }

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, MainActivity.class);
    final Bundle extras = new Bundle();
    extras.putBoolean(Const.IntentExtras.INCREMENT_NOTIFY_GROUP, true);
    extras.putBoolean(Const.IntentExtras.RESET_NOTIFY_NUMBER, true);
    resultIntent.putExtras(extras);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    mBuilder.setContentIntent(
            PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    Intent receiverIntent = new Intent(context, PowerConnectionReceiver.class);
    receiverIntent.setAction(Const.IntentActions.NOTIFY_DELETE);
    PendingIntent deleteIntent = PendingIntent.getBroadcast(context, Const.RequestCodes.RESET_NOTIFY_NUMBER,
            receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setDeleteIntent(deleteIntent);

    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // NOTIFY_ID allows updates to the notification later on.
    mNotificationManager.notify(Const.NOTIFY_ID, mBuilder.build());
}

From source file:jahirfiquitiva.iconshowcase.services.NotificationsService.java

@SuppressWarnings("ResourceAsColor")
private void pushNotification(String content, int type, int ID) {

    Preferences mPrefs = new Preferences(this);

    String appName = Utils.getStringFromResources(this, R.string.app_name);

    String title = appName, notifContent = null;

    switch (type) {
    case 1://from   w w w  . ja v  a 2 s. c  o  m
        title = getResources().getString(R.string.new_walls_notif_title, appName);
        notifContent = getResources().getString(R.string.new_walls_notif_content, content);
        break;
    case 2:
        title = appName + " " + getResources().getString(R.string.news).toLowerCase();
        notifContent = content;
        break;
    }

    // Send Notification
    NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
    notifBuilder.setAutoCancel(true);
    notifBuilder.setContentTitle(title);
    if (notifContent != null) {
        notifBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notifContent));
        notifBuilder.setContentText(notifContent);
    }
    notifBuilder.setTicker(title);
    Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notifBuilder.setSound(ringtoneUri);

    if (mPrefs.getNotifsVibrationEnabled()) {
        notifBuilder.setVibrate(new long[] { 500, 500 });
    } else {
        notifBuilder.setVibrate(null);
    }

    int ledColor = ThemeUtils.darkTheme ? ContextCompat.getColor(this, R.color.dark_theme_accent)
            : ContextCompat.getColor(this, R.color.light_theme_accent);

    notifBuilder.setColor(ledColor);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notifBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    Class appLauncherActivity = getLauncherClass(getApplicationContext());

    if (appLauncherActivity != null) {
        Intent appIntent = new Intent(this, appLauncherActivity);
        appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        appIntent.putExtra("notifType", type);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(appLauncherActivity);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(appIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        notifBuilder.setContentIntent(resultPendingIntent);
    }

    notifBuilder.setOngoing(false);

    notifBuilder.setSmallIcon(R.drawable.ic_notifications);

    Notification notif = notifBuilder.build();

    if (mPrefs.getNotifsLedEnabled()) {
        notif.ledARGB = ledColor;
    }

    notifManager.notify(ID, notif);
}

From source file:com.bluros.updater.service.UpdateCheckService.java

private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates, Intent finishedIntent) {

    if (availableUpdates == null) {
        sendBroadcast(finishedIntent);/*  w  w w.ja v a 2  s . co  m*/
        return;
    }

    // Store the last update check time and ensure boot check completed is true
    Date d = new Date();
    PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
            .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
            .putBoolean(Constants.BOOT_CHECK_COMPLETED, true).apply();

    int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
    UpdateApplication app = (UpdateApplication) getApplicationContext();

    // Write to log
    Log.i(TAG, "The update check successfully completed at " + d + " and found " + availableUpdates.size()
            + " updates (" + realUpdateCount + " newer than installed)");

    if (realUpdateCount != 0 && !app.isMainActivityActive()) {
        // There are updates available
        // The notification should launch the main app
        Intent i = new Intent(this, UpdatesSettings.class);
        i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

        Resources res = getResources();
        String text = res.getQuantityString(R.plurals.not_new_updates_found_body, realUpdateCount,
                realUpdateCount);

        // Get the notification ready
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_system_update).setWhen(System.currentTimeMillis())
                .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                .setContentTitle(res.getString(R.string.not_new_updates_found_title)).setContentText(text)
                .setContentIntent(contentIntent).setLocalOnly(true).setAutoCancel(true);

        LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
        for (UpdateInfo ui : availableUpdates) {
            if (ui.isNewerThanInstalled()) {
                realUpdates.add(ui);
            }
        }

        Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
            @Override
            public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                /* sort by date descending */
                long lhsDate = lhs.getDate();
                long rhsDate = rhs.getDate();
                if (lhsDate == rhsDate) {
                    return 0;
                }
                return lhsDate < rhsDate ? 1 : -1;
            }
        });

        NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(builder)
                .setBigContentTitle(text);
        int added = 0, count = realUpdates.size();

        for (UpdateInfo ui : realUpdates) {
            if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                inbox.addLine(ui.getName());
                added++;
            }
        }
        if (added != count) {
            inbox.setSummaryText(
                    res.getQuantityString(R.plurals.not_additional_count, count - added, count - added));
        }
        builder.setStyle(inbox);
        builder.setNumber(availableUpdates.size());

        if (count == 1) {
            i = new Intent(this, DownloadReceiver.class);
            i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
            i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
            PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            builder.addAction(R.drawable.ic_tab_download, res.getString(R.string.not_action_download),
                    downloadIntent);
        }

        // Trigger the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(R.string.not_new_updates_found_title, builder.build());
    }

    sendBroadcast(finishedIntent);
}

From source file:com.appsimobile.appsihomeplugins.dashclock.phone.SmsExtension.java

@Override
public void onUpdateData(FieldValues.Builder builder) {
    long lastUnreadThreadId = 0;
    Set<Long> unreadThreadIds = new HashSet<Long>();
    Set<String> unreadThreadParticipantNames = new HashSet<String>();
    boolean showingAllConversationParticipants = false;

    Cursor cursor = tryOpenSimpleThreadsCursor();
    if (cursor != null) {
        while (cursor.moveToNext()) {
            if (cursor.getInt(SimpleThreadsQuery.READ) == 0) {
                long threadId = cursor.getLong(SimpleThreadsQuery._ID);
                unreadThreadIds.add(threadId);
                lastUnreadThreadId = threadId;

                // Some devices will fail on tryOpenMmsSmsCursor below, so
                // store a list of participants on unread threads as a fallback.
                String recipientIdsStr = cursor.getString(SimpleThreadsQuery.RECIPIENT_IDS);
                if (!TextUtils.isEmpty(recipientIdsStr)) {
                    String[] recipientIds = TextUtils.split(recipientIdsStr, " ");
                    for (String recipientId : recipientIds) {
                        Cursor canonAddrCursor = tryOpenCanonicalAddressCursorById(Long.parseLong(recipientId));
                        if (canonAddrCursor == null) {
                            continue;
                        }//from   w  w w .  ja  v a  2  s. c  o  m
                        if (canonAddrCursor.moveToFirst()) {
                            String address = canonAddrCursor.getString(CanonicalAddressQuery.ADDRESS);
                            String displayName = getDisplayNameForContact(0, address);
                            if (!TextUtils.isEmpty(displayName)) {
                                unreadThreadParticipantNames.add(displayName);
                            }
                        }
                        canonAddrCursor.close();
                    }
                }
            }
        }
        cursor.close();

        LOGD(TAG, "Unread thread IDs: [" + TextUtils.join(", ", unreadThreadIds) + "]");
    }

    int unreadConversations = 0;
    StringBuilder names = new StringBuilder();
    cursor = tryOpenMmsSmsCursor();
    if (cursor != null) {
        // Most devices will hit this code path.
        while (cursor.moveToNext()) {
            // Get display name. SMS's are easy; MMS's not so much.
            long id = cursor.getLong(MmsSmsQuery._ID);
            long contactId = cursor.getLong(MmsSmsQuery.PERSON);
            String address = cursor.getString(MmsSmsQuery.ADDRESS);
            long threadId = cursor.getLong(MmsSmsQuery.THREAD_ID);
            if (unreadThreadIds != null && !unreadThreadIds.contains(threadId)) {
                // We have the list of all thread IDs (same as what the messaging app uses), and
                // this supposedly unread message's thread isn't in the list. This message is
                // likely an orphaned message whose thread was deleted. Not skipping it is
                // likely the cause of http://code.google.com/p/dashclock/issues/detail?id=8
                LOGD(TAG, "Skipping probably orphaned message " + id + " with thread ID " + threadId);
                continue;
            }

            ++unreadConversations;
            lastUnreadThreadId = threadId;

            if (contactId == 0 && TextUtils.isEmpty(address) && id != 0) {
                // Try MMS addr query
                Cursor addrCursor = tryOpenMmsAddrCursor(id);
                if (addrCursor != null) {
                    if (addrCursor.moveToFirst()) {
                        contactId = addrCursor.getLong(MmsAddrQuery.CONTACT_ID);
                        address = addrCursor.getString(MmsAddrQuery.ADDRESS);
                    }
                    addrCursor.close();
                }
            }

            String displayName = getDisplayNameForContact(contactId, address);

            if (names.length() > 0) {
                names.append(", ");
            }
            names.append(displayName);
        }
        cursor.close();

    } else {
        // In case the cursor is null (some Samsung devices like the Galaxy S4), use the
        // fall back on the list of participants in unread threads.
        unreadConversations = unreadThreadIds.size();
        names.append(TextUtils.join(", ", unreadThreadParticipantNames));
        showingAllConversationParticipants = true;
    }

    Intent clickIntent;
    if (unreadConversations == 1 && lastUnreadThreadId > 0) {
        clickIntent = new Intent(Intent.ACTION_VIEW, TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI
                .buildUpon().appendPath(Long.toString(lastUnreadThreadId)).build());
    } else {
        clickIntent = IntentCompat.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MESSAGING);
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(getContext(),
            DashClockHomeExtension.DASHCLOCK_EXTENSION_SMS, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    builder.leftImageResId(R.drawable.ic_extension_sms).intent(pendingIntent).header(getResources()
            .getQuantityString(R.plurals.sms_title_template, unreadConversations, unreadConversations));
    if (unreadConversations > 0) {
        builder.text(getString(showingAllConversationParticipants ? R.string.sms_body_all_participants_template
                : R.string.sms_body_template, names.toString()));
    }

    /*
            
    publishUpdate(new ExtensionData()
        .visible(unreadConversations > 0)
        .icon(R.drawable.ic_extension_sms)
        .status(Integer.toString(unreadConversations))
        .expandedTitle(
                getResources().getQuantityString(
                        R.plurals.sms_title_template, unreadConversations,
                        unreadConversations))
        .expandedBody(getString(showingAllConversationParticipants
                ? R.string.sms_body_all_participants_template
                : R.string.sms_body_template,
                names.toString()))
        .clickIntent(clickIntent));
    */
}

From source file:com.example.android.basicsyncadapter.SyncAdapter.java

/**
 * Called by the Android system in response to a request to run the sync adapter. The work required to read data from the network,
 * parse it, and store it in the content provider is done here. Extending AbstractThreadedSyncAdapter ensures that all methods
 * within SyncAdapter run on a background thread. For this reason, blocking I/O and other long-running tasks can be run
 * <em>in situ</em>, and you don't have to set up a separate thread for them.
 *
 * <p>This is where we actually perform any work required to perform a sync. {@link android.content.AbstractThreadedSyncAdapter}
 * guarantees that this will be called on a non-UI thread, so it is safe to peform blocking I/O here.
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered the sync.
 *///from  w  w w .j  av  a  2  s.co m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    try {
        InputStream stream = null;

        try {
            //Log.i(TAG, "Streaming data from network: " + FEED_URL);
            //stream = downloadUrl(location);
            stream = downloadUrl(FEED_URL);
            updateLocalFeedData(stream, syncResult);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "Feed URL is malformed", e);
        syncResult.stats.numParseExceptions++;
        return;
    } catch (IOException e) {
        Log.e(TAG, "Error reading from network: " + e.toString());
        syncResult.stats.numIoExceptions++;
        return;
    } catch (XmlPullParserException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (ParseException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (RemoteException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    }
    Log.i(TAG, "Network synchronization complete");

    //Throw notification

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Alerta de cicln tropical")
            .setContentText("Hello World!").setAutoCancel(true).setLights(0xff00ff00, 300, 100)
            .setPriority(Notification.PRIORITY_MAX);

    Intent resultIntent = new Intent(getContext(), EntryListActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Add sound
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    //Add vibrate pattern
    long[] pattern = { 0, 200, 500 };

    mBuilder.setVibrate(pattern);
    mBuilder.setSound(alarmSound);
    mBuilder.setContentIntent(resultPendingIntent);

    int mNotificationId = 001;
    NotificationManager mNotifyMgr = (NotificationManager) getContext()
            .getSystemService(Service.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

    //Wake screen
    /*WakeLock screenOn = ((PowerManager)getContext().getSystemService(Service.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK| PowerManager.ACQUIRE_CAUSES_WAKEUP, "example");
    screenOn.acquire();
            
    long endTime = System.currentTimeMillis() + 6*1000;
    while (System.currentTimeMillis() < endTime) {
    synchronized (this) {
        try {
            wait(endTime - System.currentTimeMillis());
        } catch (Exception e) {
        }
    }
    }
            
    screenOn.release();*/
}

From source file:com.android.dialer.calllog.DefaultVoicemailNotifier.java

/**
 * Updates the notification and notifies of the call with the given URI.
 *
 * Clears the notification if there are no new voicemails, and notifies if the given URI
 * corresponds to a new voicemail./*from  w w w  .  j a v a 2 s. c  o  m*/
 *
 * It is not safe to call this method from the main thread.
 */
public void updateNotification(Uri newCallUri) {
    // Lookup the list of new voicemails to include in the notification.
    // TODO: Move this into a service, to avoid holding the receiver up.
    final List<NewCall> newCalls = CallLogNotificationsHelper.getInstance(mContext).getNewVoicemails();

    if (newCalls == null) {
        // Query failed, just return.
        return;
    }

    if (newCalls.isEmpty()) {
        // No voicemails to notify about: clear the notification.
        getNotificationManager().cancel(NOTIFICATION_TAG, NOTIFICATION_ID);
        return;
    }

    Resources resources = mContext.getResources();

    // This represents a list of names to include in the notification.
    String callers = null;

    // Maps each number into a name: if a number is in the map, it has already left a more
    // recent voicemail.
    final Map<String, String> names = Maps.newHashMap();

    // Determine the call corresponding to the new voicemail we have to notify about.
    NewCall callToNotify = null;

    // Iterate over the new voicemails to determine all the information above.
    Iterator<NewCall> itr = newCalls.iterator();
    while (itr.hasNext()) {
        NewCall newCall = itr.next();

        // Skip notifying for numbers which are blocked.
        if (FilteredNumbersUtil.shouldBlockVoicemail(mContext, newCall.number, newCall.countryIso,
                newCall.dateMs)) {
            itr.remove();

            // Delete the voicemail.
            mContext.getContentResolver().delete(newCall.voicemailUri, null, null);
            continue;
        }

        // Check if we already know the name associated with this number.
        String name = names.get(newCall.number);
        if (name == null) {
            name = CallLogNotificationsHelper.getInstance(mContext).getName(newCall.number,
                    newCall.numberPresentation, newCall.countryIso);
            names.put(newCall.number, name);
            // This is a new caller. Add it to the back of the list of callers.
            if (TextUtils.isEmpty(callers)) {
                callers = name;
            } else {
                callers = resources.getString(R.string.notification_voicemail_callers_list, callers, name);
            }
        }
        // Check if this is the new call we need to notify about.
        if (newCallUri != null && newCall.voicemailUri != null
                && ContentUris.parseId(newCallUri) == ContentUris.parseId(newCall.voicemailUri)) {
            callToNotify = newCall;
        }
    }

    // All the potential new voicemails have been removed, e.g. if they were spam.
    if (newCalls.isEmpty()) {
        return;
    }

    // If there is only one voicemail, set its transcription as the "long text".
    String transcription = null;
    if (newCalls.size() == 1) {
        transcription = newCalls.get(0).transcription;
    }

    if (newCallUri != null && callToNotify == null) {
        Log.e(TAG, "The new call could not be found in the call log: " + newCallUri);
    }

    // Determine the title of the notification and the icon for it.
    final String title = resources.getQuantityString(R.plurals.notification_voicemail_title, newCalls.size(),
            newCalls.size());
    // TODO: Use the photo of contact if all calls are from the same person.
    final int icon = android.R.drawable.stat_notify_voicemail;

    Pair<Uri, Integer> info = getNotificationInfo(callToNotify);

    Notification.Builder notificationBuilder = new Notification.Builder(mContext).setSmallIcon(icon)
            .setContentTitle(title).setContentText(callers)
            .setStyle(new Notification.BigTextStyle().bigText(transcription))
            .setColor(resources.getColor(R.color.dialer_theme_color)).setSound(info.first)
            .setDefaults(info.second).setDeleteIntent(createMarkNewVoicemailsAsOldIntent()).setAutoCancel(true);

    // Determine the intent to fire when the notification is clicked on.
    final Intent contentIntent;
    // Open the call log.
    contentIntent = new Intent(mContext, DialtactsActivity.class);
    contentIntent.putExtra(DialtactsActivity.EXTRA_SHOW_TAB, ListsFragment.TAB_INDEX_VOICEMAIL);
    notificationBuilder.setContentIntent(
            PendingIntent.getActivity(mContext, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // The text to show in the ticker, describing the new event.
    if (callToNotify != null) {
        CharSequence msg = ContactDisplayUtils.getTtsSpannedPhoneNumber(resources,
                R.string.notification_new_voicemail_ticker, names.get(callToNotify.number));
        notificationBuilder.setTicker(msg);
    }
    Log.i(TAG, "Creating voicemail notification");
    getNotificationManager().notify(NOTIFICATION_TAG, NOTIFICATION_ID, notificationBuilder.build());
}

From source file:edu.mit.media.funf.configured.ConfiguredPipeline.java

private void scheduleAlarm(String action, long delayInSeconds) {
    Intent i = new Intent(this, getClass());
    i.setAction(action);/* w ww. j  av a2  s.  c  o m*/
    boolean noAlarmExists = (PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE) == null);
    if (noAlarmExists) {
        PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long delayInMilliseconds = Utils.secondsToMillis(delayInSeconds);
        long startTimeInMilliseconds = System.currentTimeMillis() + delayInMilliseconds;
        Log.i(TAG, "Scheduling alarm for '" + action + "' at " + Utils.millisToSeconds(startTimeInMilliseconds)
                + " and every " + delayInSeconds + " seconds");
        // Inexact repeating doesn't work unlesss interval is 15, 30 min, or 1, 6, or 24 hours
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, startTimeInMilliseconds, delayInMilliseconds,
                pi);
    }
}