List of usage examples for android.app NotificationManager notify
public void notify(int id, Notification notification)
From source file:com.krayzk9s.imgurholo.services.DownloadService.java
@Override protected void onHandleIntent(Intent intent) { final NotificationManager notificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); ids = intent.getParcelableArrayListExtra("ids"); albumName = "/"; downloaded = 0;//from w w w .java 2 s . co m if (ids.size() > 0) { albumName += intent.getStringExtra("albumName") + "/"; File myDirectory = new File( android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName); if (!myDirectory.exists()) { myDirectory.mkdirs(); } } for (int i = 0; i < ids.size(); i++) { try { final String type = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE) .split("/")[1]; final String id = ids.get(i).getJSONObject().getString("id"); final String link = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK); Log.d("data", ids.get(i).getJSONObject().toString()); Log.d(ImgurHoloActivity.IMAGE_DATA_TYPE, ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE).split("/")[1]); Log.d("id", ids.get(i).getJSONObject().getString("id")); Log.d(ImgurHoloActivity.IMAGE_DATA_LINK, ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK)); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setContentTitle(getString(R.string.picture_download)) .setContentText(getString(R.string.download_in_progress)) .setSmallIcon(R.drawable.icon_desaturated); Ion.with(getApplicationContext(), link).progress(new ProgressCallback() { @Override public void onProgress(int i, int i2) { notificationBuilder.setProgress(i2, i, false); } }).write(new File( android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + albumName + id + "." + type)) .setCallback(new FutureCallback<File>() { @Override public void onCompleted(Exception e, File file) { if (file == null) return; downloaded += 1; if (downloaded == ids.size()) { NotificationCompat.Builder notificationComplete = new NotificationCompat.Builder( getApplicationContext()); if (ids.size() == 1) { Intent viewImageIntent = new Intent(Intent.ACTION_VIEW); viewImageIntent.setDataAndType(Uri.fromFile(file), "image/*"); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); shareIntent.setType("image/*"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); PendingIntent viewImagePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), viewImageIntent, 0); PendingIntent sharePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), shareIntent, 0); notificationComplete.setContentTitle(getString(R.string.download_complete)) .setSmallIcon(R.drawable.icon_desaturated) .setContentText(String.format(getString(R.string.download_progress), downloaded)) .setContentIntent(viewImagePendingIntent) .addAction(R.drawable.dark_social_share, getString(R.string.share), sharePendingIntent); } else { Intent i = new Intent(Intent.ACTION_PICK); i.setDataAndType( Uri.fromFile(new File( android.os.Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES) + albumName)), "image/*"); PendingIntent viewImagePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), i, 0); notificationComplete.setContentTitle(getString(R.string.download_complete)) .setSmallIcon(R.drawable.icon_desaturated).setContentText(String .format(getString(R.string.download_progress), downloaded)) .setContentIntent(viewImagePendingIntent); } notificationManager.cancel(0); notificationManager.cancel(1); notificationManager.notify(1, notificationComplete.build()); } MediaScannerConnection.scanFile(getApplicationContext(), new String[] { android.os.Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES) + albumName + id + "." + type }, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(final String path, final Uri uri) { Log.i("Scanning", String.format("Scanned path %s -> URI = %s", path, uri.toString())); } }); } }); notificationManager.notify(0, notificationBuilder.build()); } catch (JSONException e) { Log.e("Error!", e.toString()); } } }
From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java
/** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager// w w w .j ava 2s . c o m * @param context * @param isNew if we've got a new message, show the ticker * @param uniqueThreadCount */ private static void updateNotification(Context context, boolean isNew, int uniqueThreadCount) { // TDH Log.d("NotificationDebug", "updateNotification()"); // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } // TDH Log.d("NotificationDebug", "Notifications not enabled!"); return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); // TDH: Log.d("NotificationDebug", "messageCount: " + messageCount); if (messageCount == 0) { Log.d("NotificationDebug", "WTF. Should have at least one message."); return; } NotificationInfo mostRecentNotification = sNotificationSet.first(); // TDH: Use NotificationCompat2 (and in other places but it is obvious where). final NotificationCompat2.Builder noti = new NotificationCompat2.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } // TDH Log.d("NotificationDebug", "Creating TaskStackBuilder"); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // TDH Log.d("NotificationDebug", "Created TaskStackBuilder. UniqueThreadCount: " + uniqueThreadCount); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable) mostRecentNotification.mSender.getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res .getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap(avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // TDH Log.d("NotificationDebug", "title: " + title); // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent(taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); // TDH: Can't do these yet. // .addKind(Notification.KIND_MESSAGE) // .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; if (vibrateAlways || vibrateSilent && nowSilent) { defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1) { // We've got a single message // TDH Log.d("NotificationDebug", "Single message, with text: " + mostRecentNotification.formatBigMessage(context)); // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new NotificationCompat2.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)).build(); } else { // Show a single notification -- big style with the text of the whole message notification = new NotificationCompat2.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)).build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new NotificationCompat2.BigTextStyle(noti).bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ").build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); NotificationCompat2.InboxStyle inboxStyle = new NotificationCompat2.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } // TDH Log.d("NotificationDebug", "Showing notification: " + notification); nm.notify(NOTIFICATION_ID, notification); }
From source file:com.chen.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *//*from w w w .j av a 2s. c om*/ private static void validateNotifications(Context context, final Folder folder, final Account account, boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final NotificationMap notificationMap = getNotificationMap(context); if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) { LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b", createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention); } else { LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b", notificationMap.size(), getAttention); } // The number of unread messages for this account and label. final Integer unread = notificationMap.getUnread(key); final int unreadCount = unread != null ? unread.intValue() : 0; final Integer unseen = notificationMap.getUnseen(key); int unseenCount = unseen != null ? unseen.intValue() : 0; Cursor cursor = null; try { final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon(); uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString()); // Do not allow this quick check to disrupt any active network-enabled conversation // cursor. uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK, Boolean.FALSE.toString()); cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION, null, null, null); if (cursor == null) { // This folder doesn't exist. LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist"); clearFolderNotification(context, account, folder, false); return; } final int cursorUnseenCount = cursor.getCount(); // Make sure the unseen count matches the number of items in the cursor. But, we don't // want to overwrite a 0 unseen count that was specified in the intent if (unseenCount != 0 && unseenCount != cursorUnseenCount) { LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count. unseen: %d cursor count: %d", unseenCount, cursorUnseenCount); unseenCount = cursorUnseenCount; } // For the purpose of the notifications, the unseen count should be capped at the num of // unread conversations. if (unseenCount > unreadCount) { unseenCount = unreadCount; } final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder); if (unseenCount == 0) { LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s", LogUtils.sanitizeName(LOG_TAG, account.name), LogUtils.sanitizeName(LOG_TAG, folder.persistentId)); nm.cancel(notificationId); return; } // We now have all we need to create the notification and the pending intent PendingIntent clickIntent; NotificationCompat.Builder notification = new NotificationCompat.Builder(context); notification.setSmallIcon(R.drawable.stat_notify_email); notification.setTicker(account.name); final long when; final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId); if (oldWhen != 0) { when = oldWhen; } else { when = System.currentTimeMillis(); } notification.setWhen(when); // The timestamp is now stored in the notification, so we can remove it from here NotificationActionUtils.sNotificationTimestamps.delete(notificationId); // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a // notification. Also this intent gets fired when the user taps on a notification as // the AutoCancel flag has been set final Intent cancelNotificationIntent = new Intent( MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS); cancelNotificationIntent.setPackage(context.getPackageName()); cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri)); cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account); cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder); notification.setDeleteIntent( PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0)); // Ensure that the notification is cleared when the user selects it notification.setAutoCancel(true); boolean eventInfoConfigured = false; final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox); final FolderPreferences folderPreferences = new FolderPreferences(context, account.getEmailAddress(), folder, isInbox); if (isInbox) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getEmailAddress()); moveNotificationSetting(accountPreferences, folderPreferences); } if (!folderPreferences.areNotificationsEnabled()) { LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying"); // Don't notify return; } if (unreadCount > 0) { // How can I order this properly? if (cursor.moveToNext()) { final Intent notificationIntent; // Launch directly to the conversation, if there is only 1 unseen conversation final boolean launchConversationMode = (unseenCount == 1); if (launchConversationMode) { notificationIntent = createViewConversationIntent(context, account, folder, cursor); } else { notificationIntent = createViewConversationIntent(context, account, folder, null); } Analytics.getInstance().sendEvent("notification_create", launchConversationMode ? "conversation" : "conversation_list", folder.getTypeDescription(), unseenCount); if (notificationIntent == null) { LogUtils.e(LOG_TAG, "Null intent when building notification"); return; } // Amend the click intent with a hint that its source was a notification, // but remove the hint before it's used to generate notification action // intents. This prevents the following sequence: // 1. generate single notification // 2. user clicks reply, then completes Compose activity // 3. main activity launches, gets FROM_NOTIFICATION hint in intent notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true); clickIntent = PendingIntent.getActivity(context, -1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION); configureLatestEventInfoFromConversation(context, account, folderPreferences, notification, cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when); eventInfoConfigured = true; } } final boolean vibrate = folderPreferences.isNotificationVibrateEnabled(); final String ringtoneUri = folderPreferences.getNotificationRingtoneUri(); final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled(); if (!ignoreUnobtrusiveSetting && notifyOnce) { // If the user has "unobtrusive notifications" enabled, only alert the first time // new mail is received in this account. This is the default behavior. See // bugs 2412348 and 2413490. notification.setOnlyAlertOnce(true); } LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name), Boolean.toString(folderPreferences.isNotificationVibrateEnabled())); int defaults = 0; /* * We do not want to notify if this is coming back from an Undo notification, hence the * oldWhen check. */ if (getAttention && oldWhen == 0) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.name); if (accountPreferences.areNotificationsEnabled()) { if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri)); LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s", LogUtils.sanitizeName(LOG_TAG, account.name), vibrate, ringtoneUri); } } // TODO(skennedy) Why do we do any of the above if we're just going to bail here? if (eventInfoConfigured) { defaults |= Notification.DEFAULT_LIGHTS; notification.setDefaults(defaults); if (oldWhen != 0) { // We do not want to display the ticker again if we are re-displaying this // notification (like from an Undo notification) notification.setTicker(null); } nm.notify(notificationId, notification.build()); } else { LogUtils.i(LOG_TAG, "event info not configured - not notifying"); } } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java
private void showNotify(int paramInt, String paramString1, String paramString2, String paramString3) { if (!getConfig().getBoolean("hide_notify", false)) { long l = System.currentTimeMillis(); FragmentActivity localFragmentActivity = getContext(); Object localObject = new Intent(getContext(), patchActivity.class); localObject = PendingIntent.getActivity(getContext(), 0, (Intent) localObject, 0); NotificationManager localNotificationManager = (NotificationManager) getContext() .getSystemService("notification"); paramString2 = new Notification(2130837552, paramString2, l); new Notification(); paramString2.setLatestEventInfo(localFragmentActivity, paramString1, paramString3, (PendingIntent) localObject); localNotificationManager.notify(paramInt, paramString2); }/*from w ww. j a v a 2s . c o m*/ }