private void setNotificationLargeIcon( Bundle extras, String packageName, Resources resources, NotificationCompat.Builder mBuilder) { String gcmLargeIcon = extras.getString(IMAGE); // from gcm if (gcmLargeIcon != null && !"".equals(gcmLargeIcon)) { if (gcmLargeIcon.startsWith("http://") || gcmLargeIcon.startsWith("https://")) { mBuilder.setLargeIcon(getBitmapFromURL(gcmLargeIcon)); Log.d(LOG_TAG, "using remote large-icon from gcm"); } else { AssetManager assetManager = getAssets(); InputStream istr; try { istr = assetManager.open(gcmLargeIcon); Bitmap bitmap = BitmapFactory.decodeStream(istr); mBuilder.setLargeIcon(bitmap); Log.d(LOG_TAG, "using assets large-icon from gcm"); } catch (IOException e) { int largeIconId = 0; largeIconId = resources.getIdentifier(gcmLargeIcon, DRAWABLE, packageName); if (largeIconId != 0) { Bitmap largeIconBitmap = BitmapFactory.decodeResource(resources, largeIconId); mBuilder.setLargeIcon(largeIconBitmap); Log.d(LOG_TAG, "using resources large-icon from gcm"); } else { Log.d(LOG_TAG, "Not setting large icon"); } } } } }
public static void sendNotification(Context context, String codigo) { mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, // MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.notification_ginrob) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentTitle("Novo Usuario") .setVibrate(new long[] {0, 500, 500, 200, 500}) .setPriority(NotificationCompat.PRIORITY_HIGH) .setStyle( new NotificationCompat.BigTextStyle() .bigText( " Codigo de Requisicao: " + codigo + ". Um novo usuário deseja realizar um cadastro, compartilhe o código para liberar o cadastro.")) .setContentText("Requisição de Novo Usuario"); Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.notification_red); mBuilder.setLargeIcon(bm); // mBuilder.setContentIntent(contentIntent); Notification notification = mBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(AndroidSystemUtil.randInt(), notification); }
public static void sendNotification( Context context, String title, String author, String message) { mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); int color; if (author.equals("activated")) { color = context.getResources().getColor(R.color.red); } else { color = context.getResources().getColor(R.color.green); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.notification_ginrob) .setColor(color) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentTitle(title) .setVibrate(new long[] {0, 500, 500, 200, 500}) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentText(author + ": " + message); Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.notification_red); mBuilder.setLargeIcon(bm); mBuilder.setContentIntent(contentIntent); Notification notification = mBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(AndroidSystemUtil.randInt(), notification); }
public void updateNotificationIcon(Bitmap icon) { if (icon != null) { mNotificationBuilder.setLargeIcon(icon); } mNotificationManager.notify(mNotificationId, mNotificationBuilder.build()); }
public static NotificationCompat.Builder getBaseBuilder(Context ctx, boolean setAutoCancel) { Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(ctx); notifBuilder.setSound(defaultSoundUri); notifBuilder.setAutoCancel(setAutoCancel); notifBuilder.setSmallIcon(R.drawable.ic_notification); // Notification styles changed since Lollipop if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { int color; // We have to check the M version for the deprecation of the method getColor() if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { color = ctx.getResources().getColor(R.color.highlight_light); } else { color = ctx.getResources().getColor(R.color.highlight_light); } notifBuilder.setColor(color); } else { // in older versions, we show the App logo notifBuilder.setLargeIcon( BitmapFactory.decodeResource(ctx.getResources(), MobileLearning.APP_LOGO)); } return notifBuilder; }
private void updateNotificationContent() { builder.setContentTitle(songTitle); builder.setContentText(songArtist); builder.setContentInfo( String.format(context.getString(R.string.notification_drink), this.currentMinute)); builder.setLargeIcon(coverArt); notificationManager.notify(notificationId, builder.build()); }
private NotificationCompat.Builder setNotification(final long id) { DownloadInfoRunnable info = getDownload(id); final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); // TODO Intent onClick = new Intent(); onClick.setClassName( getPackageName(), /*Aptoide.getConfiguration().*/ getStartActivityClass().getName()); onClick.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); onClick.setAction(Intent.ACTION_VIEW); onClick.putExtra("fromDownloadNotification", true); // The PendingIntent to launch our activity if the user selects this notification PendingIntent onClickAction = PendingIntent.getActivity( getApplicationContext(), 0, onClick, PendingIntent.FLAG_UPDATE_CURRENT); int size = DownloadUtils.dpToPixels(getApplicationContext(), 36); Bitmap icon = null; try { // icon = // DownloadUtils.decodeSampledBitmapFromResource(ImageLoader.getInstance().getDiscCache().get(info.getDownload().getIcon()).getAbsolutePath(), size, size); icon = GlideUtils.downloadOnlyFromCache( Aptoide.getContext(), info.getDownload().getIcon(), size, size); } catch (Exception e) { e.printStackTrace(); } mBuilder.setOngoing(true); mBuilder.setContentTitle( getString(R.string.aptoide_downloading, Aptoide.getConfiguration().getMarketName())); mBuilder.setContentText(info.getDownload().getName()); if (icon != null) mBuilder.setLargeIcon(icon); mBuilder.setSmallIcon(android.R.drawable.stat_sys_download); mBuilder.setProgress(0, 0, true); mBuilder.setContentIntent(onClickAction); // Log.d("download-trace", "ETA: " + info.getEta()); if (info.getEta() > 0) { String remaining = DownloadUtils.formatEta(info.getEta(), ""); mBuilder.setContentInfo("ETA: " + (!remaining.equals("") ? remaining : "0s")); } return mBuilder; }
/** Update the notification with the new track info */ private void updateNotification() { if (mLastSong != null) { Bitmap scaledArt = Bitmap.createScaledBitmap( mLastSong.getArt(), mNotificationWidth, mNotificationHeight, false); mNotifyBuilder.setLargeIcon(scaledArt); mNotifyBuilder.setContentTitle(mLastSong.getArtist()); mNotifyBuilder.setContentText(mLastSong.getTitle() + " / " + mLastSong.getAlbum()); } else { mNotifyBuilder.setContentTitle(App.mApp.getString(R.string.app_name)); mNotifyBuilder.setContentText(App.mApp.getString(R.string.player_nosong)); } mNotificationManager.notify(App.NOTIFY_ID, mNotifyBuilder.build()); }
private void showNotification() { mNotifMGR = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); // notification for the task bar NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.ic_music); builder.setContentTitle(mArtist[mSong]); builder.setContentText(mTitle[mSong]); builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong])); builder.setAutoCancel(false); builder.setOngoing(true); NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle(); style.setBigContentTitle(mArtist[mSong]); style.setSummaryText(mTitle[mSong]); style.bigLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_music)); style.bigPicture(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong])); builder.setStyle(style); Intent skipIntent = new Intent(PREV_TRACK); PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_rew, "Last Track", pIntent); skipIntent = new Intent(NEXT_TRACK); pIntent = PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_ff, "Next Track", pIntent); Intent clickIntent = new Intent(this, MainActivity.class); clickIntent.putExtra(MainFragment.EXTRA_TITLE_UPDATE, mTitle[mSong]); clickIntent.putExtra(MainFragment.EXTRA_COVER_UPDATE, mArtwork[mSong]); clickIntent.putExtra(MainFragment.EXTRA_ARTIST_UPDATE, mArtist[mSong]); clickIntent.putExtra(MainFragment.EXTRA_SONG_DURATION, mPlayer.getDuration()); PendingIntent pendClickIntent = PendingIntent.getActivity(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendClickIntent); Notification notification = builder.build(); startForeground(NOTIF_ID, notification); }
private void showPostUpdateNotification() { // Remove the old one mNotificationManager.cancel(NOTIFICATION_ID); mBuilder = new NotificationCompat.Builder(getApplicationContext()); mBuilder.setTicker(getString(R.string.finishedTraktMovieSync)); mBuilder.setContentTitle(getString(R.string.finishedTraktMovieSync)); mBuilder.setSmallIcon(R.drawable.done); mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.done)); mBuilder.setOngoing(false); mBuilder.setAutoCancel(true); mBuilder.setOnlyAlertOnce(true); // Build notification Notification updateNotification = mBuilder.build(); // Show the notification mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIFICATION_ID + 1000, updateNotification); }
private void setupNotification() { // Setup up notification mBuilder = new NotificationCompat.Builder(getApplicationContext()); mBuilder.setSmallIcon(R.drawable.ic_action_tv); mBuilder.setTicker(getString(R.string.syncMovies)); mBuilder.setContentTitle(getString(R.string.syncMovies)); mBuilder.setContentText(getString(R.string.updatingMovieInfo)); mBuilder.setOngoing(true); mBuilder.setOnlyAlertOnce(true); mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_tv)); // Build notification Notification updateNotification = mBuilder.build(); // Show the notification mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIFICATION_ID, updateNotification); // Tell the system that this is an ongoing notification, so it shouldn't be killed startForeground(NOTIFICATION_ID, updateNotification); }
public void sendNotification() { builder.setSmallIcon(R.drawable.ic_launcher); // if(Constants.NOTIFICATION_CONDUCTOR==typeNototification){ // builder.setAutoCancel(false); // } // // else{ // builder.setAutoCancel(true); // // } builder.setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); if (contentTitle != null) builder.setContentTitle(contentTitle); if (contentText != null) builder.setContentText(contentText); if (subText != null) builder.setSubText(subText); NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, builder.build()); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Received start id " + startId + ": " + intent); if (intent != null) { // config = Config.fromByteArray(intent.getByteArrayExtra("config")); config = (Config) intent.getParcelableExtra("config"); Log.i(TAG, "Config: " + config.toString()); // Build a Notification required for running service in foreground. NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(config.getNotificationTitle()); builder.setContentText(config.getNotificationText()); builder.setSmallIcon(android.R.drawable.ic_menu_mylocation); if (config.getNotificationIcon() != null) { builder.setSmallIcon(getPluginResource(config.getSmallNotificationIcon())); builder.setLargeIcon( BitmapFactory.decodeResource( getApplication().getResources(), getPluginResource(config.getLargeNotificationIcon()))); } if (config.getNotificationIconColor() != null) { builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor())); } setClickEvent(builder); Notification notification = builder.build(); notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR; startForeground(startId, notification); } // We want this service to continue running until it is explicitly stopped return START_REDELIVER_INTENT; }
@Override public void vaddStatNotif(final Context ctxt, final StatusMessage in) { StatusMessage m = validateStrings(in); if (m.getShow() != 1) { vcancel(ctxt, STAT_TAG, NotifUtil.STATNOTIFID); return; } if (NotifUtil.ssidStatus == NotifUtil.SSID_STATUS_UNMANAGED) { m.setStatus( new StringBuilder(ctxt.getString(R.string.unmanaged)).append(m.getStatus()).toString()); } NotificationCompat.Builder statbuilder = new NotificationCompat.Builder(ctxt); Intent intent = new Intent(ctxt, WifiFixerActivity.class) .setAction(Intent.ACTION_MAIN) .setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); statbuilder.setContentIntent(PendingIntent.getActivity(ctxt, 0, intent, 0)); statbuilder.setOnlyAlertOnce(true); statbuilder.setOngoing(true); statbuilder.setWhen(0); statbuilder.setPriority(NotificationCompat.PRIORITY_MIN); statbuilder.setSmallIcon(getIconfromSignal(m.getSignal(), ICON_SET_SMALL)); statbuilder.setLargeIcon( BitmapFactory.decodeResource( ctxt.getResources(), getIconfromSignal(m.getSignal(), ICON_SET_LARGE))); statbuilder.setContentText(m.getStatus()); statbuilder.setSubText(ctxt.getString(R.string.network_status)); statbuilder.setContentTitle(m.getSSID()); /* * Fire the notification */ notify(ctxt, NotifUtil.STATNOTIFID, STAT_TAG, statbuilder.build()); }
private void showNotification(JSONObject message) { NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); // These attributes are required final String id; try { builder.setContentTitle(message.getString(TITLE_ATTR)); builder.setContentText(message.getString(TEXT_ATTR)); id = message.getString(ID_ATTR); } catch (JSONException ex) { Log.i(LOGTAG, "Error parsing", ex); return; } Uri imageUri = Uri.parse(message.optString(SMALLICON_ATTR)); builder.setSmallIcon(BitmapUtils.getResource(imageUri, R.drawable.ic_status_logo)); JSONArray light = message.optJSONArray(LIGHT_ATTR); if (light != null && light.length() == 3) { try { builder.setLights(light.getInt(0), light.getInt(1), light.getInt(2)); } catch (JSONException ex) { Log.i(LOGTAG, "Error parsing", ex); } } boolean ongoing = message.optBoolean(ONGOING_ATTR); builder.setOngoing(ongoing); if (message.has(WHEN_ATTR)) { long when = message.optLong(WHEN_ATTR); builder.setWhen(when); } if (message.has(PRIORITY_ATTR)) { int priority = message.optInt(PRIORITY_ATTR); builder.setPriority(priority); } if (message.has(LARGE_ICON_ATTR)) { Bitmap b = BitmapUtils.getBitmapFromDataURI(message.optString(LARGE_ICON_ATTR)); builder.setLargeIcon(b); } if (message.has(PROGRESS_VALUE_ATTR) && message.has(PROGRESS_MAX_ATTR) && message.has(PROGRESS_INDETERMINATE_ATTR)) { try { final int progress = message.getInt(PROGRESS_VALUE_ATTR); final int progressMax = message.getInt(PROGRESS_MAX_ATTR); final boolean progressIndeterminate = message.getBoolean(PROGRESS_INDETERMINATE_ATTR); builder.setProgress(progressMax, progress, progressIndeterminate); } catch (JSONException ex) { Log.i(LOGTAG, "Error parsing", ex); } } JSONArray actions = message.optJSONArray(ACTIONS_ATTR); if (actions != null) { try { for (int i = 0; i < actions.length(); i++) { JSONObject action = actions.getJSONObject(i); final PendingIntent pending = buildButtonClickPendingIntent(message, action); final String actionTitle = action.getString(ACTION_TITLE_ATTR); final Uri actionImage = Uri.parse(action.optString(ACTION_ICON_ATTR)); builder.addAction( BitmapUtils.getResource(actionImage, R.drawable.ic_status_logo), actionTitle, pending); } } catch (JSONException ex) { Log.i(LOGTAG, "Error parsing", ex); } } PendingIntent pi = buildNotificationPendingIntent(message, CLICK_EVENT); builder.setContentIntent(pi); PendingIntent deletePendingIntent = buildNotificationPendingIntent(message, CLEARED_EVENT); builder.setDeleteIntent(deletePendingIntent); GeckoAppShell.notificationClient.add(id.hashCode(), builder.build()); boolean persistent = message.optBoolean(PERSISTENT_ATTR); // We add only not persistent notifications to the list since we want to purge only // them when geckoapp is destroyed. if (!persistent && !mClearableNotifications.containsKey(id)) { mClearableNotifications.put(id, message.toString()); } }
private void onNotify( final SharedPreferences prefs, final Cursor upcomingEpisodes, int count, long latestAirtime) { final Context context = getApplicationContext(); CharSequence tickerText = ""; CharSequence contentTitle = ""; CharSequence contentText = ""; PendingIntent contentIntent = null; // notification sound final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context); // vibration final boolean isVibrating = NotificationSettings.isNotificationVibrating(context); if (count == 1) { // notify in detail about one episode upcomingEpisodes.moveToFirst(); final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE); final String airs = Utils.formatToTimeAndDay(upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[ 0]; final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); tickerText = getString(R.string.upcoming_show, showTitle); contentTitle = showTitle + " " + Utils.getEpisodeNumber( this, upcomingEpisodes.getInt(NotificationQuery.SEASON), upcomingEpisodes.getInt(NotificationQuery.NUMBER)); contentText = getString(R.string.upcoming_show_detailed, airs, network); Intent notificationIntent = new Intent(context, EpisodesActivity.class); notificationIntent.putExtra( EpisodesActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); contentIntent = PendingIntent.getActivity(context, REQUEST_CODE_SINGLE_EPISODE, notificationIntent, 0); } else if (count > 1) { // notify about multiple episodes tickerText = getString(R.string.upcoming_episodes); contentTitle = getString(R.string.upcoming_episodes_number, count); contentText = getString(R.string.upcoming_display); Intent notificationIntent = new Intent(context, UpcomingRecentActivity.class); notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); contentIntent = PendingIntent.getActivity(context, REQUEST_CODE_MULTIPLE_EPISODES, notificationIntent, 0); } final NotificationCompat.Builder nb = new NotificationCompat.Builder(context); if (AndroidUtils.isJellyBeanOrHigher()) { // JELLY BEAN and above if (count == 1) { // single episode upcomingEpisodes.moveToFirst(); final String imagePath = upcomingEpisodes.getString(NotificationQuery.POSTER); nb.setLargeIcon(ImageProvider.getInstance(context).getImage(imagePath, true)); final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE); final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW); final SpannableStringBuilder bigText = new SpannableStringBuilder(); bigText.append(episodeTitle); bigText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, bigText.length(), 0); bigText.append("\n"); bigText.append(episodeSummary); nb.setStyle( new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText)); // Action button to check in Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class); checkInActionIntent.putExtra( QuickCheckInActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN, checkInActionIntent, 0); nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent); } else { // multiple episodes NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); // display at most the first five final int displayCount = Math.min(count, 5); for (int i = 0; i < displayCount; i++) { if (upcomingEpisodes.moveToPosition(i)) { // add show title, air time and network final SpannableStringBuilder lineText = new SpannableStringBuilder(); lineText.append(upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE)); lineText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, lineText.length(), 0); lineText.append(" "); String airs = Utils.formatToTimeAndDay( upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[0]; String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); lineText.append(getString(R.string.upcoming_show_detailed, airs, network)); inboxStyle.addLine(lineText); } } // tell if we could not display all episodes if (count > 5) { inboxStyle.setSummaryText(getString(R.string.more, count - 5)); } nb.setStyle(inboxStyle); nb.setContentInfo(String.valueOf(count)); } } else { // ICS and below if (count == 1) { // single episode upcomingEpisodes.moveToFirst(); final String posterPath = upcomingEpisodes.getString(NotificationQuery.POSTER); nb.setLargeIcon(ImageProvider.getInstance(context).getImage(posterPath, true)); } } // If the string is empty, the user chose silent... if (ringtoneUri.length() != 0) { // ...otherwise set the specified ringtone nb.setSound(Uri.parse(ringtoneUri)); } if (isVibrating) { nb.setVibrate(VIBRATION_PATTERN); } nb.setDefaults(Notification.DEFAULT_LIGHTS); nb.setWhen(System.currentTimeMillis()); nb.setAutoCancel(true); nb.setTicker(tickerText); nb.setContentTitle(contentTitle); nb.setContentText(contentText); nb.setContentIntent(contentIntent); nb.setSmallIcon(R.drawable.ic_notification); nb.setPriority(NotificationCompat.PRIORITY_DEFAULT); Intent i = new Intent(this, NotificationService.class); i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); PendingIntent deleteIntent = PendingIntent.getService(this, 1, i, 0); nb.setDeleteIntent(deleteIntent); // build the notification Notification notification = nb.build(); // use string resource id, always unique within app final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(R.string.upcoming_show, notification); }
public void setLargeIcon(int res) { builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), res)); }
private void showNotification() { String[] projection = new String[] { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_SUBSCRIPTION_ID, PodcastProvider.COLUMN_SUBSCRIPTION_TITLE, PodcastProvider.COLUMN_SUBSCRIPTION_THUMBNAIL, }; Cursor c = getContentResolver() .query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null); if (c == null) return; if (c.isAfterLast()) { c.close(); return; } PodcastCursor podcast = new PodcastCursor(c); // both paths use the pendingintent Intent showIntent = new Intent(this, MainActivity.class); PendingIntent showPendingIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setWhen(0) .setContentTitle(podcast.getTitle()) .setContentText(podcast.getSubscriptionTitle()) .setContentIntent(showPendingIntent) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT); // set up pause intent Intent pauseIntent = new Intent(this, PlayerService.class); // use data to make intent unique pauseIntent.setData(Uri.parse("podax://playercommand/playpause")); pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE); pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, Constants.PAUSE_MEDIABUTTON); PendingIntent pausePendingIntent = PendingIntent.getService(this, 0, pauseIntent, 0); // set up forward intent Intent forwardIntent = new Intent(this, ActivePodcastReceiver.class); forwardIntent.setData(Constants.ACTIVE_PODCAST_DATA_FORWARD); PendingIntent forwardPendingIntent = PendingIntent.getService(this, 0, forwardIntent, 0); Bitmap subscriptionBitmap = Helper.getCachedImage(this, podcast.getSubscriptionThumbnailUrl(), 128, 128); if (subscriptionBitmap != null) builder.setLargeIcon(subscriptionBitmap); if (PlayerStatus.getPlayerState(this) == PlayerStates.PLAYING) builder.addAction( R.drawable.ic_media_pause_normal, getString(R.string.pause), pausePendingIntent); else builder.addAction( R.drawable.ic_media_play_normal, getString(R.string.play), pausePendingIntent); builder.addAction( R.drawable.ic_media_ff_normal, getString(R.string.fast_forward), forwardPendingIntent); Notification notification = builder.build(); startForeground(Constants.NOTIFICATION_PLAYING, notification); c.close(); }
@Override protected void onHandleIntent(Intent intent) { mDManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); long downloadManagerID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); Log.d("DOWNLOAD", "DONE " + downloadManagerID); manager = new MagazineManager(this); Magazine magazine = manager.findByDownloadManagerID(downloadManagerID, Magazine.TABLE_DOWNLOADED_MAGAZINES); if (magazine != null) { DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(downloadManagerID); Cursor c = mDManager.query(q); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); if (status == DownloadManager.STATUS_SUCCESSFUL) { // process download String srcFileName = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); magazine.clearMagazineDir(); magazine.makeMagazineDir(); StorageUtils.move( srcFileName, magazine.isSample() ? magazine.getSamplePdfPath() : magazine.getItemPath()); } } c.close(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle( magazine.getTitle() + (magazine.isSample() ? " sample" : "") + " downloaded") .setContentText("Click to read"); // Create large icon from magazine cover png Resources res = getResources(); int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height); int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width); mBuilder.setLargeIcon( SystemHelper.decodeSampledBitmapFromFile(magazine.getPngPath(), height, width)); // TODO show magazine cover as large image Intent resultIntent = new Intent(this, MuPDFActivity.class); resultIntent.setAction(Intent.ACTION_VIEW); resultIntent.setData( Uri.parse(magazine.isSample() ? magazine.getSamplePdfPath() : magazine.getItemPath())); resultIntent.putExtra(Magazine.FIELD_TITLE, magazine.getTitle()); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MuPDFActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mBuilder.setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify((int) magazine.getDownloadManagerId(), mBuilder.build()); Date date = Calendar.getInstance().getTime(); String downloadDate = new SimpleDateFormat(" dd.MM.yyyy").format(date); magazine.setDownloadDate(downloadDate); manager.removeDownloadedMagazine(this, magazine); manager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true); EventBus.getDefault().post(new LoadPlistEvent()); EventBus.getDefault().post(new MagazineDownloadedEvent(magazine)); startLinksDownload(this, magazine); magazine.makeCompleteFile(magazine.isSample()); } else { // Asset downloaded manager.setAssetDownloaded(downloadManagerID); DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(downloadManagerID); Cursor c = mDManager.query(q); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); if (status == DownloadManager.STATUS_SUCCESSFUL) { // process download String srcFileName = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); StorageUtils.move(srcFileName, manager.getAssetFilename(downloadManagerID)); } } c.close(); } }
private void sendNotification(String msg, String webId, Bitmap bitmap) { final PostsDataSource postsDataSource = new PostsDataSource(this); final String webId2 = webId; final String msg2 = msg; final Bitmap bitmap1 = bitmap; postsDataSource.open(); if (postsDataSource.countRow( DB.POST_TABLE, DB.POST_COLUMNS, DB.POST_COLUMN_WEB_ID + " = ? ", new String[] {webId}, null) == 0) { new WebClient( URL.buildUrl(WebUrl.POST_URL, "20", webId, null, null, null, null), new Response.Listener<String>() { @Override public void onResponse(String response) { List<Post> postList; postList = WebJSONParser.postParseFeed(response); postsDataSource.insertPosts(postList); Post post = postsDataSource.getPost( DB.POST_COLUMN_WEB_ID + " = ? ", new String[] {webId2}, null); Intent intent = new Intent(getApplicationContext(), DetailActivity.class); intent.putExtra("id", Long.toString(post.getPostId())); intent.putExtra("type", post.getType()); intent.putExtra("categoryId", "no"); intent.putExtra("webId", webId2); // PendingIntent resultPendingIntent = // PendingIntent.getActivity(getApplicationContext(), 0, intent, // PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mNotifyBuilder; NotificationManager mNotificationManager; mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotifyBuilder = new NotificationCompat.Builder(getApplicationContext()) .setContentTitle(msg2) .setTicker(msg2) .setSmallIcon(R.drawable.ic_launcher); if (bitmap1 != null) { mNotifyBuilder.setLargeIcon(bitmap1); } if (post.getContent() != null) { mNotifyBuilder.setContentText(Html.fromHtml(post.getContent())); } // Creates an explicit intent for an Activity in your app // Intent resultIntent = new Intent(this, testActivity.class); // The stack builder object will contain an artificial back stack // for // the // started Activity. // This ensures that navigating backward from the Activity leads out // of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext()); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(HomeActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mNotifyBuilder.setContentIntent(resultPendingIntent); // mNotifyBuilder.setContentIntent(resultPendingIntent); // Set Vibrate, Sound and Light int defaults = 0; defaults = defaults | Notification.DEFAULT_LIGHTS; defaults = defaults | Notification.DEFAULT_VIBRATE; defaults = defaults | Notification.DEFAULT_SOUND; mNotifyBuilder.setDefaults(defaults); // Set the content for Notification mNotifyBuilder.setContentText(msg2); // Set autocancel mNotifyBuilder.setAutoCancel(true); mNotifyBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); // Post a notification mNotificationManager.notify(notifyID, mNotifyBuilder.build()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) {} }, Request.Priority.HIGH); return; } else { Post post = postsDataSource.getPost(DB.POST_COLUMN_WEB_ID + " = ? ", new String[] {webId}, null); Intent intent = new Intent(this, DetailActivity.class); intent.putExtra("id", Long.toString(post.getPostId())); intent.putExtra("type", post.getType()); intent.putExtra("categoryId", "no"); intent.putExtra("webId", webId); // PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, intent, // PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mNotifyBuilder; NotificationManager mNotificationManager; mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotifyBuilder = new NotificationCompat.Builder(this) .setContentTitle(msg) .setTicker(msg) .setSmallIcon(R.drawable.ic_launcher); if (bitmap1 != null) { mNotifyBuilder.setLargeIcon(bitmap1); } if (post.getContent() != null) { mNotifyBuilder.setContentText(Html.fromHtml(post.getContent())); } // Creates an explicit intent for an Activity in your app // Intent resultIntent = new Intent(this, testActivity.class); // The stack builder object will contain an artificial back stack // for // the // started Activity. // This ensures that navigating backward from the Activity leads out // of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(HomeActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mNotifyBuilder.setContentIntent(resultPendingIntent); // mNotifyBuilder.setContentIntent(resultPendingIntent); // Set Vibrate, Sound and Light int defaults = 0; defaults = defaults | Notification.DEFAULT_LIGHTS; defaults = defaults | Notification.DEFAULT_VIBRATE; defaults = defaults | Notification.DEFAULT_SOUND; mNotifyBuilder.setDefaults(defaults); // mNotifyBuilder.setContentText(msg); mNotifyBuilder.setAutoCancel(true); mNotifyBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); mNotificationManager.notify(notifyID, mNotifyBuilder.build()); } }
@Override public Builder setLargeIcon(Bitmap icon) { super.setLargeIcon(icon); return this; }
public void postNotification(int id) { if (notificationItems.size() == 0) { return; } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setContentTitle(notificationTitle); mBuilder.setSmallIcon(R.drawable.ic_stat_icon); mBuilder.setLargeIcon( BitmapFactory.decodeResource( context.getResources(), R.drawable.ic_action_notification_dark)); if (notificationItems.size() > 1) { // inbox style NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(); try { inbox.setBigContentTitle(notificationTitle); } catch (Exception e) { } if (notificationItems.size() <= 5) { for (String s : notificationItems) { inbox.addLine(Html.fromHtml(s)); } } else { for (int i = 0; i < 5; i++) { inbox.addLine(Html.fromHtml(notificationItems.get(i))); } int extra = notificationItems.size() - 5; if (extra > 1) { inbox.setSummaryText("+" + extra + " " + context.getString(R.string.items)); } else { inbox.setSummaryText("+" + extra + " " + context.getString(R.string.item)); } } mBuilder.setStyle(inbox); mBuilder.setContentText(notificationItems.size() + " " + context.getString(R.string.items)); } else { // big text style NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText(Html.fromHtml(notificationItems.get(0))); bigText.setBigContentTitle(notificationTitle); mBuilder.setStyle(bigText); mBuilder.setContentText(Html.fromHtml(notificationItems.get(0))); } if (!useSecondAccount) { mBuilder.setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, RedirectToActivity.class), 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); } 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); } // Pebble notification if (sharedPrefs.getBoolean("pebble_notification", false)) { NotificationUtils.sendAlertToPebble(context, notificationTitle, notificationItems.get(0)); } // Light Flow notification NotificationUtils.sendToLightFlow(context, notificationTitle, notificationItems.get(0)); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(id, mBuilder.build()); }
public void showNotifications(List<String> contacts) { if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) { Conversation[] conversations = Database.getInstance(applicationContext).getConversations(preferences.getDid()); for (Conversation conversation : conversations) { if (!conversation.isUnread() || !contacts.contains(conversation.getContact()) || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity()) .getContact() .equals(conversation.getContact()))) { continue; } String smsContact = Utils.getContactName(applicationContext, conversation.getContact()); if (smsContact == null) { smsContact = Utils.getFormattedPhoneNumber(conversation.getContact()); } String allSmses = ""; String mostRecentSms = ""; boolean initial = true; for (Message message : conversation.getMessages()) { if (message.getType() == Message.Type.INCOMING && message.isUnread()) { if (initial) { allSmses = message.getText(); mostRecentSms = message.getText(); initial = false; } else { allSmses = message.getText() + "\n" + allSmses; } } else { break; } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext); notificationBuilder.setContentTitle(smsContact); notificationBuilder.setContentText(mostRecentSms); notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp); notificationBuilder.setPriority(Notification.PRIORITY_HIGH); notificationBuilder.setSound( Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound())); notificationBuilder.setLights(0xFFAA0000, 1000, 5000); if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) { notificationBuilder.setVibrate(new long[] {0, 250, 250, 250}); } else { notificationBuilder.setVibrate(new long[] {0}); } notificationBuilder.setColor(0xFFAA0000); notificationBuilder.setAutoCancel(true); notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses)); Bitmap largeIconBitmap; try { largeIconBitmap = MediaStore.Images.Media.getBitmap( applicationContext.getContentResolver(), Uri.parse( Utils.getContactPhotoUri(applicationContext, conversation.getContact()))); largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false); largeIconBitmap = Utils.applyCircularMask(largeIconBitmap); notificationBuilder.setLargeIcon(largeIconBitmap); } catch (Exception ignored) { } Intent intent = new Intent(applicationContext, ConversationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext); stackBuilder.addParentStack(ConversationActivity.class); stackBuilder.addNextIntent(intent); notificationBuilder.setContentIntent( stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT)); Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } else { //noinspection deprecation replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); } replyIntent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); PendingIntent replyPendingIntent = PendingIntent.getActivity( applicationContext, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder( R.drawable.ic_reply_white_24dp, applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent); notificationBuilder.addAction(replyAction.build()); Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class); markAsReadIntent.putExtra( applicationContext.getString(R.string.conversation_extra_contact), conversation.getContact()); PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast( applicationContext, 0, markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder( R.drawable.ic_drafts_white_24dp, applicationContext.getString(R.string.notifications_button_mark_read), markAsReadPendingIntent); notificationBuilder.addAction(markAsReadAction.build()); int id; if (notificationIds.get(conversation.getContact()) != null) { id = notificationIds.get(conversation.getContact()); } else { id = notificationIdCount++; notificationIds.put(conversation.getContact(), id); } NotificationManager notificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id, notificationBuilder.build()); } } }
private boolean updateNotification(final Context context) { Log.d(TAG, "updateNotification()"); lastUpdate = System.currentTimeMillis(); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); ArrayList<Timer> timers = new ArrayList<Timer>(); mNow = System.currentTimeMillis(); mNextTarget = 0; boolean alert = false; Log.d(TAG, "mNow: " + mNow); for (int j = 0; j < Timer.TIMER_IDS.length; j++) { Timer t = new Timer(context, j); timers.add(t); long tt = t.getTarget(); Log.d(TAG, "target(" + j + "): " + tt); if (tt > 0) { if (mNextTarget == 0 || tt < mNextTarget) { mNextTarget = tt; } if (tt < mNow) { alert = true; t.reset(context); } } } Log.d(TAG, "mNextTarget: " + mNextTarget); NotificationCompat.Builder b = new NotificationCompat.Builder(context); b.setPriority(1000); Intent i = new Intent(context, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); b.setContentTitle(context.getString(R.string.app_name)); b.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); b.setSmallIcon(R.drawable.ic_stat_timer); b.setAutoCancel(false); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // GB- b.setContentText( context.getString( R.string.notification_text, timers.get(0).getFormatted(), timers.get(1).getFormatted(), timers.get(2).getFormatted())); } else { // HC+ RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.notification); for (int j = 0; j < Timer.TIMER_IDS.length; j++) { v.setTextViewText(Timer.TIMER_IDS[j], timers.get(j).getFormatted().toString()); Intent ij = new Intent(Timer.TIMER_KEYS[j], null, context, UpdateReceiver.class); v.setOnClickPendingIntent( Timer.TIMER_IDS[j], PendingIntent.getBroadcast(context, 0, ij, PendingIntent.FLAG_UPDATE_CURRENT)); } v.setOnClickPendingIntent( R.id.settings, PendingIntent.getActivity( context, 0, new Intent(context, SettingsActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)); b.setContent(v); } if (mNextTarget <= 0 && !alert) { // we don't need any notification b.setOngoing(false); nm.notify(0, b.build()); return false; } else if (alert) { // show notification without running Timer b.setOngoing(mNextTarget > 0); SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); if (p.getBoolean("vibrate", true)) { b.setVibrate(VIBRATE); } String n = p.getString("notification", null); if (n == null) { // default b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } else if (n.length() > 1) { try { b.setSound(Uri.parse(n)); } catch (Exception e) { Log.e(TAG, "invalid notification uri", e); b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } } // else: silent nm.notify(0, b.build()); return true; } else { // show notification with running Timer b.setOngoing(true); nm.notify(0, b.build()); return true; } }
@NonNull public static Notification buildNotification( @NonNull Context context, final int id, @NonNull Object... objects) { final Resources res = context.getResources(); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.stat_acdisplay) .setColor(App.ACCENT_COLOR) .setAutoCancel(true); PendingIntent pi = null; switch (id) { case App.ID_NOTIFY_TEST: { NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle() .bigText(res.getString(R.string.notification_test_message_large)); builder .setStyle(bts) .setContentTitle(res.getString(R.string.app_name)) .setContentText(res.getString(R.string.notification_test_message)) .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher)) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); break; } case App.ID_NOTIFY_BATH: { CharSequence contentText = (CharSequence) objects[0]; Intent contentIntent = (Intent) objects[1]; // Build notification pi = PendingIntent.getActivity( context, id, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder .setContentTitle(res.getString(R.string.service_bath)) .setContentText(contentText) .setPriority(Notification.PRIORITY_MIN); break; } case App.ID_NOTIFY_INIT: { builder .setSmallIcon(R.drawable.stat_notify) .setContentTitle(res.getString(R.string.app_name)) .setContentText(res.getString(R.string.notification_init_text)) .setPriority(Notification.PRIORITY_MIN); break; } case App.ID_NOTIFY_APP_AUTO_DISABLED: { CharSequence summary = (CharSequence) objects[0]; NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle() .bigText(res.getString(R.string.permissions_auto_disabled)) .setSummaryText(summary); builder .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher)) .setContentTitle(res.getString(R.string.app_name)) .setContentText(res.getString(R.string.permissions_auto_disabled)) .setPriority(Notification.PRIORITY_HIGH) .setStyle(bts); break; } default: throw new IllegalArgumentException(); } if (pi == null) { pi = PendingIntent.getActivity( context, id, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); } return builder.setContentIntent(pi).build(); }
private void showNotification( int playState, int audioPath, String title, String artist, String album, Bitmap artwork) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle(title); if (artwork != null) { builder.setLargeIcon(artwork); } int icon = R.drawable.ic_launcher; if (audioPath == AUDIO_PATH_SPEAKER) { icon = R.drawable.ic_speaker; } else if (audioPath == AUDIO_PATH_A2DP) { icon = R.drawable.ic_a2dp; } else if (audioPath == AUDIO_PATH_WIRED) { icon = R.drawable.ic_wired; } builder.setSmallIcon(icon); builder.setTicker(title); builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setContentText(artist); builder.setSubText(album); PendingIntent pendingIntent = null; Intent intent = new Intent(this, PlaybackService.class); String keyTop; String action; if (playState == PLAY_STATE_PAUSED) { action = ACTION_PAUSE; keyTop = "Pause"; icon = android.R.drawable.ic_media_pause; intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_TRACK_DOWN); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_previous, "Prev", pendingIntent); } else { action = ACTION_PLAY; keyTop = "Play"; icon = android.R.drawable.ic_media_play; intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_STOP); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_delete, "Stop", pendingIntent); } intent = new Intent(this, PlaybackService.class); intent.setAction(action); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(icon, keyTop, pendingIntent); intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_TRACK_UP); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_next, "Next", pendingIntent); intent = new Intent(this, SimpleMusicPlayer.class); pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); startForeground(R.id.notification_id, builder.build()); // startForeground(R.id.notification_id, new // NotificationCompat.InboxStyle(builder).addLine("test1").addLine("test2").build()); }