List of usage examples for android.app PendingIntent FLAG_ONE_SHOT
int FLAG_ONE_SHOT
To view the source code for android.app PendingIntent FLAG_ONE_SHOT.
Click Source Link
From source file:com.google.firebase.quickstart.fcm.java.MyFirebaseMessagingService.java
/** * Create and show a simple notification containing the received FCM message. * * @param messageBody FCM message body received. *///from ww w . j av a2 s.c o m private void sendNotification(String messageBody) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_channel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_stat_ic_notification).setContentTitle(getString(R.string.fcm_message)) .setContentText(messageBody).setAutoCancel(true).setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); }
From source file:com.oliversride.wordryo.Utils.java
public static void postNotification(Context context, Intent intent, String title, String body, int id) { /* nextRandomInt: per this link http://stackoverflow.com/questions/10561419/scheduling-more-than-one-pendingintent-to-same-activity-using-alarmmanager one way to avoid getting the same PendingIntent for similar Intents is to send a different second param each time, though the docs say that param's ignored. *//* w ww. j a v a 2 s. c o m*/ PendingIntent pi = null == intent ? null : PendingIntent.getActivity(context, Utils.nextRandomInt(), intent, PendingIntent.FLAG_ONE_SHOT); int defaults = Notification.FLAG_AUTO_CANCEL; if (CommonPrefs.getSoundNotify(context)) { defaults |= Notification.DEFAULT_SOUND; } if (CommonPrefs.getVibrateNotify(context)) { defaults |= Notification.DEFAULT_VIBRATE; } Notification notification = new NotificationCompat.Builder(context).setContentIntent(pi) .setSmallIcon(R.drawable.notify) //.setTicker(body) //.setWhen(time) .setAutoCancel(true).setDefaults(defaults).setContentTitle(title).setContentText(body).build(); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(id, notification); }
From source file:chron.carlosrafael.chatapp.MyFirebaseMessagingService.java
/** * Create and show a simple notification containing the received FCM message. * * @param messageBody FCM message body received. *//* w w w . j ava 2s . com*/ private void sendNotification(String messageBody, String messageUser) { //Se ainda nao tiver clicado na notification a ID vai ter que ser a mesma //Se tiver clicado entao temos que gerar uma nova ID int notificationID; if (NotificationHandler.createNewNotification) { Random generator = new Random(); notificationID = generator.nextInt(100); NotificationHandler.onGoingNotificationID = notificationID; //Dizendo que nao precisa criar uma nova notificacao ate o usuario clicar na notificacao e abrir o chat NotificationHandler.createNewNotification = false; } else { notificationID = NotificationHandler.onGoingNotificationID; } //Quando o usuario clicar ele vai pra o MainActivity Intent intent = new Intent(this, HomeActivity.class); //Botando um Extra para quando ele abrir por um Intent vindo do notification ele para de acumular as //mensagens de notificacao intent.putExtra("fromNotification", true); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("New message in chat") .setContentText(messageUser + " : " + messageBody).setAutoCancel(true).setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); //Adicionando as mensagens no ArrayList que mantem todas as mensagens da notification que ainda vai ser vista NotificationHandler.notificationMessages.add(messageUser + " : " + messageBody); //Se nao eh pra criar uma nova notificacao entao temos que: // 1 - Adicionar essa mensagem como a ultima no ArrayList da notificacao // 2 - Ler o ArrayList pra criar o InboxStyle com todas as mensagens if (!NotificationHandler.createNewNotification) { int numMessages = NotificationHandler.notificationMessages.size(); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String title = (numMessages > 1) ? String.valueOf(numMessages) + " new messages in chat" : String.valueOf(numMessages) + " new message in chat"; inboxStyle.setBigContentTitle(title); //inboxStyle.addLine(messageBody); for (int i = 0; i < NotificationHandler.notificationMessages.size(); i++) { //notificationBuilder.setContentText("Tamo no loop" + String.valueOf(i)) notificationBuilder.setNumber(NotificationHandler.notificationMessages.size()); inboxStyle.addLine(NotificationHandler.notificationMessages.get(i)); //inboxStyle.addLine("Tamo no loop" + String.valueOf(i)); // Because the ID remains unchanged, the existing notification is // updated. // notificationManager.notify( // notificationID, // notificationBuilder.build()); } notificationBuilder.setStyle(inboxStyle); } notificationManager.notify(notificationID, notificationBuilder.build()); // Issue the notification here. //notificationManager.notify(notificationID /* ID of notification */, notificationBuilder.build()); }
From source file:com.orangelabs.rcs.ri.messaging.filetransfer.FileTransferIntentService.java
/** * Add file transfer notification//from w ww. j av a2s . c om * * @param invitation Intent invitation * @param ftDao the file transfer data object */ private void addFileTransferInvitationNotification(Intent invitation, FileTransferDAO ftDao) { ContactId contact = ftDao.getContact(); if (ftDao.getContact() == null) { if (LogUtils.isActive) { Log.e(LOGTAG, "addFileTransferInvitationNotification failed: cannot parse contact"); } return; } Intent intent = ReceiveFileTransfer.forgeInvitationIntent(this, ftDao, invitation); /* * If the PendingIntent has the same operation, action, data, categories, components, and * flags it will be replaced. Invitation should be notified individually so we use a random * generator to provide a unique request code and reuse it for the notification. */ int uniqueId = Utils.getUniqueIdForPendingIntent(); PendingIntent pi = PendingIntent.getActivity(this, uniqueId, intent, PendingIntent.FLAG_ONE_SHOT); String displayName = RcsContactUtil.getInstance(this).getDisplayName(contact); String title = getString(R.string.title_recv_file_transfer); String message = getString(R.string.label_from_args, displayName); /* Send notification */ NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); Notification notif = buildNotification(pi, title, message); notificationManager.notify(uniqueId, notif); }
From source file:fr.bde_eseo.eseomega.gcmpush.MyGcmListenerService.java
/** * Create and show a simple notification containing the received GCM message. * * @param message GCM message received./*from ww w. j ava 2 s.c o m*/ */ private void sendNotification(int intentID, String title, String message, double versionPush) { // prepare intent Intent intent = null; if (versionPush > Constants.NOTIF_VERSION) { intentID = Constants.NOTIF_UPDATE; title = Constants.NOTIF_UPDATE_TITLE; message = Constants.NOTIF_UPDATE_TEXT; } switch (intentID) { case Constants.NOTIF_GENERAL: case Constants.NOTIF_NEWS: case Constants.NOTIF_EVENTS: case Constants.NOTIF_CLUBS: case Constants.NOTIF_CAFET: case Constants.NOTIF_TIPS: case Constants.NOTIF_CONNECT: default: intent = new Intent(this, MainActivity.class); intent.putExtra(Constants.KEY_MAIN_INTENT, intentID); if (intentID == Constants.NOTIF_GENERAL) { intent.putExtra(Constants.KEY_MAIN_TITLE, title); intent.putExtra(Constants.KEY_MAIN_MESSAGE, message); } break; case Constants.NOTIF_GANTIER_ENABLE: // Enable in prefs the game access UserProfile userProfileEn = new UserProfile(); userProfileEn.readProfilePromPrefs(this); userProfileEn.enableGuy(); userProfileEn.registerProfileInPrefs(this); break; case Constants.NOTIF_GANTIER_DISABLE: // Enable in prefs the game access UserProfile userProfileDis = new UserProfile(); userProfileDis.readProfilePromPrefs(this); userProfileDis.disableGuy(); userProfileDis.registerProfileInPrefs(this); break; case Constants.NOTIF_GANTIER: intent = new Intent(this, GantierActivity.class); intent.putExtra(Constants.KEY_GANTIER_INTENT, intentID); break; case Constants.NOTIF_UPDATE: final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object try { intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)); } catch (android.content.ActivityNotFoundException anfe) { Toast.makeText(MyGcmListenerService.this, "Erreur d'accs Play Store", Toast.LENGTH_SHORT).show(); } break; } // Attach intent to notification, only if has intent if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_ONE_SHOT); long[] pattern = { 0, 100, 250, 100, 250, 100 }; Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notif) // Only small icon for Lollipop .setContentTitle(title).setContentText(message).setAutoCancel(true) .setLights(Color.BLUE, 1000, 3000).setColor(this.getResources().getColor(R.color.md_blue_800)) .setVibrate(pattern).setSound(defaultSoundUri).setContentIntent(pendingIntent) .setStyle(new NotificationCompat.BigTextStyle().bigText(message)); // Big icon for previous version (older than Lollipop) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { notificationBuilder .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)); } NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // Random notification ID notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build()); } }
From source file:com.android.deskclock.data.TimerNotificationBuilderPreN.java
@Override public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) { final Timer timer = unexpired.get(0); final long remainingTime = timer.getRemainingTime(); // Generate some descriptive text, a title, and some actions based on timer states. final String contentText; final String contentTitle; @DrawableRes/*from ww w . ja v a 2 s . co m*/ int firstActionIconId, secondActionIconId = 0; @StringRes int firstActionTitleId, secondActionTitleId = 0; Intent firstActionIntent, secondActionIntent = null; if (unexpired.size() == 1) { contentText = formatElapsedTimeUntilExpiry(context, remainingTime); if (timer.isRunning()) { // Single timer is running. if (TextUtils.isEmpty(timer.getLabel())) { contentTitle = context.getString(R.string.timer_notification_label); } else { contentTitle = timer.getLabel(); } firstActionIconId = R.drawable.ic_pause_24dp; firstActionTitleId = R.string.timer_pause; firstActionIntent = new Intent(context, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_add_24dp; secondActionTitleId = R.string.timer_plus_1_min; secondActionIntent = new Intent(context, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } else { // Single timer is paused. contentTitle = context.getString(R.string.timer_paused); firstActionIconId = R.drawable.ic_start_24dp; firstActionTitleId = R.string.sw_resume_button; firstActionIntent = new Intent(context, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_reset_24dp; secondActionTitleId = R.string.sw_reset_button; secondActionIntent = new Intent(context, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } } else { if (timer.isRunning()) { // At least one timer is running. final String timeRemaining = formatElapsedTimeUntilExpiry(context, remainingTime); contentText = context.getString(R.string.next_timer_notif, timeRemaining); contentTitle = context.getString(R.string.timers_in_use, unexpired.size()); } else { // All timers are paused. contentText = context.getString(R.string.all_timers_stopped_notif); contentTitle = context.getString(R.string.timers_stopped, unexpired.size()); } firstActionIconId = R.drawable.ic_reset_24dp; firstActionTitleId = R.string.timer_reset_all; firstActionIntent = TimerService.createResetUnexpiredTimersIntent(context); } // Intent to load the app and show the timer when the notification is tapped. final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()) .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification); final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setOngoing(true) .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText) .setContentTitle(contentTitle).setContentIntent(pendingShowApp) .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setColor(ContextCompat.getColor(context, R.color.default_background)); final PendingIntent action1 = Utils.pendingServiceIntent(context, firstActionIntent); final String action1Title = context.getString(firstActionTitleId); builder.addAction(firstActionIconId, action1Title, action1); if (secondActionIntent != null) { final PendingIntent action2 = Utils.pendingServiceIntent(context, secondActionIntent); final String action2Title = context.getString(secondActionTitleId); builder.addAction(secondActionIconId, action2Title, action2); } final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final Intent updateNotification = TimerService.createUpdateNotificationIntent(context); if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) { // Schedule a callback to update the time-sensitive information of the running timer. final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS; final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange; TimerModel.schedulePendingIntent(am, triggerTime, pi); } else { // Cancel the update notification callback. final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { am.cancel(pi); pi.cancel(); } } return builder.build(); }
From source file:com.ph1ash.dexter.beeplepaper.BeeplePaperService.java
protected void displayLoginNotification() { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.common_full_open_on_phone).setContentTitle("BeeplePaper - Verify Login") .setContentText("Verify your Facebook login for to allow BeeplePaper to update."); 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_ONE_SHOT); mBuilder.setContentIntent(resultPendingIntent); Notification notif = mBuilder.build(); notif.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, notif); }
From source file:com.perfilyev.vkmessengerlite.MessagingService.java
private PendingIntent createPendingIntent() { Intent intent = new Intent(this, DialogsListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return PendingIntent.getActivity(this, REQUEST_CODE, intent, PendingIntent.FLAG_ONE_SHOT); }
From source file:com.androzic.plugin.tracker.SMSReceiver.java
@Override public void onReceive(Context context, Intent intent) { String Sender = ""; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Log.e(TAG, "SMS received"); Bundle extras = intent.getExtras();//from www . ja v a2s . c om if (extras == null) return; StringBuilder messageBuilder = new StringBuilder(); Object[] pdus = (Object[]) extras.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); String text = msg.getMessageBody(); Sender = msg.getDisplayOriginatingAddress(); Log.w(TAG, "Sender: " + Sender); if (text == null) continue; messageBuilder.append(text); } String text = messageBuilder.toString(); boolean flexMode = prefs.getBoolean(context.getString(R.string.pref_tracker_use_flex_mode), context.getResources().getBoolean(R.bool.def_flex_mode)); Log.i(TAG, "SMS: " + text); Tracker tracker = new Tracker(); if (!parseXexunTK102(text, tracker) && !parseJointechJT600(text, tracker) && !parseTK102Clone1(text, tracker) && !(parseFlexMode(text, tracker) && flexMode)) return; if (tracker.message != null) { tracker.message = tracker.message.trim(); if ("".equals(tracker.message)) tracker.message = null; } tracker.sender = Sender; if (!"".equals(tracker.sender)) { // Save tracker data TrackerDataAccess dataAccess = new TrackerDataAccess(context); dataAccess.updateTracker(tracker); try { Application application = Application.getApplication(); tracker = dataAccess.getTracker(tracker.sender);//get latest positon of tracker application.sendTrackerOnMap(dataAccess, tracker); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } dataAccess.close(); context.sendBroadcast(new Intent(Application.TRACKER_DATE_RECEIVED_BROADCAST)); // Show notification boolean notifications = prefs.getBoolean(context.getString(R.string.pref_tracker_notifications), context.getResources().getBoolean(R.bool.def_notifications)); if (notifications) { Intent i = new Intent("com.androzic.COORDINATES_RECEIVED"); i.putExtra("title", tracker.message != null ? tracker.message : tracker.name); i.putExtra("sender", tracker.name); i.putExtra("origin", context.getApplicationContext().getPackageName()); i.putExtra("lat", tracker.latitude); i.putExtra("lon", tracker.longitude); String msg = context.getString(R.string.notif_text, tracker.name); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setContentTitle(context.getString(R.string.app_name)); if (tracker.message != null) builder.setContentText(tracker.name + ": " + tracker.message); else builder.setContentText(msg); PendingIntent contentIntent = PendingIntent.getBroadcast(context, (int) tracker._id, i, PendingIntent.FLAG_ONE_SHOT); builder.setContentIntent(contentIntent); builder.setSmallIcon(R.drawable.ic_stat_tracker); builder.setTicker(msg); builder.setWhen(tracker.time); int defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND; boolean vibrate = prefs.getBoolean(context.getString(R.string.pref_tracker_vibrate), context.getResources().getBoolean(R.bool.def_vibrate)); if (vibrate) defaults |= Notification.DEFAULT_VIBRATE; builder.setDefaults(defaults); builder.setAutoCancel(true); Notification notification = builder.build(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify((int) tracker._id, notification); } // Conceal SMS boolean concealsms = prefs.getBoolean(context.getString(R.string.pref_tracker_concealsms), context.getResources().getBoolean(R.bool.def_concealsms)); if (concealsms) abortBroadcast(); } }
From source file:com.ghosthawk.salard.GCM.MyGcmListenerService.java
private void sendNotification(String message) { Intent intent = new Intent(this, SellHomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setTicker("Salard ").setSmallIcon(R.drawable.rating_bar_full) .setContentTitle("Salard ? ?.").setContentText(message) .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); }