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.prod.intelligent7.engineautostart.ConnectDaemonService.java
void startHourlyCheckAlarm() { if (scheduleAlarm != null) { alarmManager.cancel(scheduleAlarm); //return; }//w w w . j av a2 s .c o m Intent jIntent = new Intent(this, ConnectDaemonService.class); //M1-00 (cool) or M1-01 (warm) jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_HOUR); jIntent.setAction(ALARM_HOUR); scheduleAlarm = PendingIntent.getService(this, ++alarmRequestId % 100 + 500, jIntent, PendingIntent.FLAG_ONE_SHOT); alarmManager.set(AlarmManager.RTC_WAKEUP, 1 * 60 * 60 * 1000 + System.currentTimeMillis(), scheduleAlarm); Log.i("ALARM_SET", "restart check alarm set for 1 hour"); //startScheduledJobs(); }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
void startScheduleAlarm() { if (scheduleAlarm != null) { alarmManager.cancel(scheduleAlarm); //return; }/*from w w w .j a v a 2s . c om*/ Intent jIntent = new Intent(this, ConnectDaemonService.class); //M1-00 (cool) or M1-01 (warm) jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_DONE); scheduleAlarm = PendingIntent.getService(this, ++alarmRequestId, jIntent, PendingIntent.FLAG_ONE_SHOT); alarmManager.set(AlarmManager.RTC_WAKEUP, 1 * 60 * 60 * 1000 + System.currentTimeMillis(), scheduleAlarm); Log.i("ALARM_SET", "restart new alarm set for 1 hour"); startScheduledJobs(); }
From source file:com.android.deskclock.data.TimerModel.java
/** * Updates the notification controlling unexpired timers. This notification is only displayed * when the application is not open./* ww w. j ava 2 s . c om*/ */ void updateNotification() { // Notifications should be hidden if the app is open. if (mNotificationModel.isApplicationInForeground()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Filter the timers to just include unexpired ones. final List<Timer> unexpired = new ArrayList<>(); for (Timer timer : getMutableTimers()) { if (timer.isRunning() || timer.isPaused()) { unexpired.add(timer); } } // If no unexpired timers exist, cancel the notification. if (unexpired.isEmpty()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Sort the unexpired timers to locate the next one scheduled to expire. Collections.sort(unexpired, Timer.EXPIRY_COMPARATOR); 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 int firstActionIconId, secondActionIconId = 0; @StringRes int firstActionTitleId, secondActionTitleId = 0; Intent firstActionIntent, secondActionIntent = null; if (unexpired.size() == 1) { contentText = formatElapsedTimeUntilExpiry(remainingTime); if (timer.isRunning()) { // Single timer is running. if (TextUtils.isEmpty(timer.getLabel())) { contentTitle = mContext.getString(R.string.timer_notification_label); } else { contentTitle = timer.getLabel(); } firstActionIconId = R.drawable.ic_pause_24dp; firstActionTitleId = R.string.timer_pause; firstActionIntent = new Intent(mContext, 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(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } else { // Single timer is paused. contentTitle = mContext.getString(R.string.timer_paused); firstActionIconId = R.drawable.ic_start_24dp; firstActionTitleId = R.string.sw_resume_button; firstActionIntent = new Intent(mContext, 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(mContext, 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(remainingTime); contentText = mContext.getString(R.string.next_timer_notif, timeRemaining); contentTitle = mContext.getString(R.string.timers_in_use, unexpired.size()); } else { // All timers are paused. contentText = mContext.getString(R.string.all_timers_stopped_notif); contentTitle = mContext.getString(R.string.timers_stopped, unexpired.size()); } firstActionIconId = R.drawable.ic_reset_24dp; firstActionTitleId = R.string.timer_reset_all; firstActionIntent = TimerService.createResetUnexpiredTimersIntent(mContext); } // Intent to load the app and show the timer when the notification is tapped. final Intent showApp = new Intent(mContext, 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(mContext, 0, showApp, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).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); final PendingIntent firstAction = PendingIntent.getService(mContext, 0, firstActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String firstActionTitle = mContext.getString(firstActionTitleId); builder.addAction(firstActionIconId, firstActionTitle, firstAction); if (secondActionIntent != null) { final PendingIntent secondAction = PendingIntent.getService(mContext, 0, secondActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String secondActionTitle = mContext.getString(secondActionTitleId); builder.addAction(secondActionIconId, secondActionTitle, secondAction); } // Update the notification. final Notification notification = builder.build(); final int notificationId = mNotificationModel.getUnexpiredTimerNotificationId(); mNotificationManager.notify(notificationId, notification); final Intent updateNotification = TimerService.createUpdateNotificationIntent(mContext); 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(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS; final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange; schedulePendingIntent(triggerTime, pi); } else { // Cancel the update notification callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { mAlarmManager.cancel(pi); pi.cancel(); } } }
From source file:com.irccloud.android.Notifications.java
@SuppressLint("NewApi") private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title, String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network, String auto_messages[]) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()); NotificationCompat.Builder builder = new NotificationCompat.Builder( IRCCloudApplication.getInstance().getApplicationContext()) .setContentTitle(title + ((network != null) ? (" (" + network + ")") : "")) .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker) .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify) .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources() .getColor(R.color.dark_blue)) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false); if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) { if (prefs.getBoolean("notify_vibrate", true)) builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE); String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound"); if (ringtone != null && ringtone.length() > 0) builder.setSound(Uri.parse(ringtone)); }// w w w . j ava2 s .c o m int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1")); if (led_color == 1) { if (prefs.getBoolean("notify_vibrate", true)) builder.setDefaults( android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE); else builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS); } else if (led_color == 2) { builder.setLights(0xFF0000FF, 500, 500); } SharedPreferences.Editor editor = prefs.edit(); editor.putLong("lastNotificationTime", System.currentTimeMillis()); editor.commit(); Intent i = new Intent(); i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity")); i.putExtra("bid", bid); i.setData(Uri.parse("bid://" + bid)); Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources() .getString(R.string.DISMISS_NOTIFICATION)); dismiss.setData(Uri.parse("irccloud-dismiss://" + bid)); dismiss.putExtra("bid", bid); dismiss.putExtra("eids", eids); PendingIntent dismissPendingIntent = PendingIntent.getBroadcast( IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent( PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setDeleteIntent(dismissPendingIntent); if (replyIntent != null) { WearableExtender extender = new WearableExtender(); PendingIntent replyPendingIntent = PendingIntent.getService( IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT); extender.addAction( new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent) .addRemoteInput( new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()) .build()); if (count > 1 && wear_text != null) extender.addPage( new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext()) .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true)) .build()); NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder( title + ((network != null) ? (" (" + network + ")") : "")) .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent, new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()); if (auto_messages != null) { for (String m : auto_messages) { if (m != null && m.length() > 0) { unreadConvBuilder.addMessage(m); } } } else { unreadConvBuilder.addMessage(text); } unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000); builder.extend(extender) .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build())); } if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) { i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class); i.setData(Uri.parse("irccloud-bid://" + bid)); i.putExtras(replyIntent); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent quickReplyIntent = PendingIntent.getActivity( IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent); } android.app.Notification notification = builder.build(); RemoteViews contentView = new RemoteViews( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification); contentView.setTextViewText(R.id.title, title + " (" + network + ")"); contentView.setTextViewText(R.id.text, (count == 1) ? Html.fromHtml(text) : (count + " unread highlights.")); contentView.setLong(R.id.time, "setTime", eids[0] / 1000); notification.contentView = contentView; if (Build.VERSION.SDK_INT >= 16 && big_text != null) { RemoteViews bigContentView = new RemoteViews( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification_expanded); bigContentView.setTextViewText(R.id.title, title + (!title.equals(network) ? (" (" + network + ")") : "")); bigContentView.setTextViewText(R.id.text, big_text); bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000); if (count > 3) { bigContentView.setViewVisibility(R.id.more, View.VISIBLE); bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more"); } else { bigContentView.setViewVisibility(R.id.more, View.GONE); } if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) { bigContentView.setViewVisibility(R.id.actions, View.VISIBLE); bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE); i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class); i.setData(Uri.parse("irccloud-bid://" + bid)); i.putExtras(replyIntent); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent quickReplyIntent = PendingIntent.getActivity( IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT); bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent); } notification.bigContentView = bigContentView; } return notification; }
From source file:me.cpwc.nibblegram.android.NotificationsController.java
private void showOrUpdateNotification(boolean notifyAboutLast) { if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { dismissNotification();/*from w w w. j a va 2s .co m*/ return; } try { ConnectionsManager.getInstance().resumeNetworkMaybe(); MessageObject lastMessageObject = pushMessages.get(0); long dialog_id = lastMessageObject.getDialogId(); int mid = lastMessageObject.messageOwner.id; int chat_id = lastMessageObject.messageOwner.to_id.chat_id; int user_id = lastMessageObject.messageOwner.to_id.user_id; if (user_id == 0) { user_id = lastMessageObject.messageOwner.from_id; } else if (user_id == UserConfig.getClientUserId()) { user_id = lastMessageObject.messageOwner.from_id; } TLRPC.User user = MessagesController.getInstance().getUser(user_id); TLRPC.Chat chat = null; if (chat_id != 0) { chat = MessagesController.getInstance().getChat(chat_id); } TLRPC.FileLocation photoPath = null; boolean notifyDisabled = false; int needVibrate = 0; String choosenSoundPath = null; int ledColor = 0xff00ff00; boolean inAppSounds = false; boolean inAppVibrate = false; boolean inAppPreview = false; boolean inAppPriority = false; int priority = 0; int priority_override = 0; int vibrate_override = 0; SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notify_override = preferences.getInt("notify2_" + dialog_id, 0); if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { notifyDisabled = true; } String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); if (!notifyDisabled) { inAppSounds = preferences.getBoolean("EnableInAppSounds", true); inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); inAppPreview = preferences.getBoolean("EnableInAppPreview", true); inAppPriority = preferences.getBoolean("EnableInAppPriority", false); vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); priority_override = preferences.getInt("priority_" + dialog_id, 3); choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); if (chat_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } needVibrate = preferences.getInt("vibrate_group", 0); priority = preferences.getInt("priority_group", 1); ledColor = preferences.getInt("GroupLed", 0xff00ff00); } else if (user_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } needVibrate = preferences.getInt("vibrate_messages", 0); priority = preferences.getInt("priority_group", 1); ledColor = preferences.getInt("MessagesLed", 0xff00ff00); } if (preferences.contains("color_" + dialog_id)) { ledColor = preferences.getInt("color_" + dialog_id, 0); } if (priority_override != 3) { priority = priority_override; } if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5) || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) { needVibrate = vibrate_override; } if (!ApplicationLoader.mainInterfacePaused) { if (!inAppSounds) { choosenSoundPath = null; } if (!inAppVibrate) { needVibrate = 2; } if (!inAppPriority) { priority = 0; } else if (priority == 2) { priority = 1; } } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if ((int) dialog_id != 0) { if (pushDialogs.size() == 1) { if (chat_id != 0) { intent.putExtra("chatId", chat_id); } else if (user_id != 0) { intent.putExtra("userId", user_id); } } if (pushDialogs.size() == 1) { if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } } else { if (pushDialogs.size() == 1) { intent.putExtra("encId", (int) (dialog_id >> 32)); } } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); String name = null; boolean replace = true; if ((int) dialog_id == 0 || pushDialogs.size() > 1) { name = LocaleController.getString("AppName", R.string.AppName); replace = false; } else { if (chat != null) { name = chat.title; } else { name = ContactsController.formatName(user.first_name, user.last_name); } } String detailText = null; if (pushDialogs.size() == 1) { detailText = LocaleController.formatPluralString("NewMessages", total_unread_count); } else { detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size())); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setAutoCancel(true).setNumber(total_unread_count) .setContentIntent(contentIntent).setGroup("messages").setGroupSummary(true); if (priority == 0) { mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT); } else if (priority == 1) { mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); } else if (priority == 2) { mBuilder.setPriority(NotificationCompat.PRIORITY_MAX); } mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE); if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { mBuilder.addPerson("tel:+" + user.phone); } /*Bundle bundle = new Bundle(); bundle.putString(NotificationCompat.EXTRA_PEOPLE, ); mBuilder.setExtras()*/ String lastMessage = null; String lastMessageFull = null; if (pushMessages.size() == 1) { String message = lastMessageFull = getStringForMessage(pushMessages.get(0), false); //lastMessage = getStringForMessage(pushMessages.get(0), true); lastMessage = lastMessageFull; if (message == null) { return; } if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } mBuilder.setContentText(message); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } else { mBuilder.setContentText(detailText); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(name); int count = Math.min(10, pushMessages.size()); for (int i = 0; i < count; i++) { String message = getStringForMessage(pushMessages.get(i), false); if (message == null) { continue; } if (i == 0) { lastMessageFull = message; //lastMessage = getStringForMessage(pushMessages.get(i), true); lastMessage = lastMessageFull; } if (pushDialogs.size() == 1) { if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } } inboxStyle.addLine(message); } inboxStyle.setSummaryText(detailText); mBuilder.setStyle(inboxStyle); } if (photoPath != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50", null); if (img != null) { mBuilder.setLargeIcon(img.getBitmap()); } } if (!notifyDisabled) { if (ApplicationLoader.mainInterfacePaused || inAppPreview) { if (lastMessage.length() > 100) { lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "..."; } mBuilder.setTicker(lastMessage); } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (choosenSoundPath.equals(defaultPath)) { /*MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI); mediaPlayer.prepare(); mediaPlayer.start();*/ mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); } else { mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); } } if (ledColor != 0) { mBuilder.setLights(ledColor, 1000, 1000); } if (needVibrate == 2) { mBuilder.setVibrate(new long[] { 0, 0 }); } else if (needVibrate == 1) { mBuilder.setVibrate(new long[] { 0, 100, 0, 100 }); } else if (needVibrate == 0 || needVibrate == 4) { mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE); } else if (needVibrate == 3) { mBuilder.setVibrate(new long[] { 0, 1000 }); } } else { mBuilder.setVibrate(new long[] { 0, 0 }); } notificationManager.notify(1, mBuilder.build()); if (preferences.getBoolean("EnablePebbleNotifications", false)) { sendAlertToPebble(lastMessageFull); } showWearNotifications(notifyAboutLast); scheduleNotificationRepeat(); } catch (Exception e) { FileLog.e("tmessages", e); } }
From source file:com.sean.takeastand.alarmprocess.AlarmService.java
private void GetDeviceLastStep(Intent intent) { Intent stepDetectorIntent = new Intent(this, StandDtectorTM.class); stepDetectorIntent.setAction(com.heckbot.standdtector.Constants.DEVICE_LAST_STEP); Intent returnIntent = new Intent(com.heckbot.standdtector.Constants.DEVICE_LAST_STEP); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, returnIntent, PendingIntent.FLAG_ONE_SHOT); stepDetectorIntent.putExtra("pendingIntent", pendingIntent); startService(stepDetectorIntent);/* w w w . j av a 2 s. c o m*/ //error handling if no step detector results are returned. mHandler = new Handler(); int tenSecondMillis = 10000; Runnable lastStepReceiverTimeout = new StepCounterTimeoutRunnable(intent); mHandler.postDelayed(lastStepReceiverTimeout, tenSecondMillis); }
From source file:com.sean.takeastand.alarmprocess.AlarmService.java
private void GetWearLastStep(Intent intent) { Intent wearStepDetectorIntent = new Intent(this, StandDtectorTM.class); wearStepDetectorIntent.setAction(com.heckbot.standdtector.Constants.WEAR_LAST_STEP); Intent returnIntent = new Intent(com.heckbot.standdtector.Constants.WEAR_LAST_STEP); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, returnIntent, PendingIntent.FLAG_ONE_SHOT); wearStepDetectorIntent.putExtra("pendingIntent", pendingIntent); startService(wearStepDetectorIntent); //error handling if no step detector results are returned. mHandler = new Handler(); int tenSecondMillis = 10000; Runnable lastWearStepReceiverTimeout = new WearStepCounterTimeoutRunnable(intent); mHandler.postDelayed(lastWearStepReceiverTimeout, tenSecondMillis); }
From source file:com.negaheno.android.NotificationsController.java
private void showOrUpdateNotification(boolean notifyAboutLast) { if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { dismissNotification();/* ww w . j a v a 2 s .c o m*/ return; } try { ConnectionsManager.getInstance().resumeNetworkMaybe(); MessageObject lastMessageObject = pushMessages.get(0); long dialog_id = lastMessageObject.getDialogId(); int mid = lastMessageObject.messageOwner.id; int chat_id = lastMessageObject.messageOwner.to_id.chat_id; int user_id = lastMessageObject.messageOwner.to_id.user_id; if (user_id == 0) { user_id = lastMessageObject.messageOwner.from_id; } else if (user_id == UserConfig.getClientUserId()) { user_id = lastMessageObject.messageOwner.from_id; } TLRPC.User user = MessagesController.getInstance().getUser(user_id); TLRPC.Chat chat = null; if (chat_id != 0) { chat = MessagesController.getInstance().getChat(chat_id); } TLRPC.FileLocation photoPath = null; boolean notifyDisabled = false; int needVibrate = 0; String choosenSoundPath = null; int ledColor = 0xff00ff00; boolean inAppSounds = false; boolean inAppVibrate = false; boolean inAppPreview = false; boolean inAppPriority = false; int priority = 0; int priority_override = 0; int vibrate_override = 0; SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notify_override = preferences.getInt("notify2_" + dialog_id, 0); if (notify_override == 3) { int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0); if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) { notify_override = 2; } } if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { notifyDisabled = true; } boolean use_smart_notify = preferences.getBoolean("smart_notify_" + dialog_id, false); Long smart_notify_timeframe = preferences.getLong("smart_notify_timeframe_" + dialog_id, 1); int smart_notify_max_count = preferences.getInt("smart_notify_max_count_" + dialog_id, 1); if (chat_id != 0 && use_smart_notify) { if (chat.sound_timestamps == null) chat.sound_timestamps = new LinkedList<>(); boolean shouldAdd = true; Date firstNotification = chat.sound_timestamps.peek(); Date currentDate = new Date(); if (firstNotification != null) { if (currentDate.getTime() - firstNotification.getTime() < smart_notify_timeframe * 1000 && chat.sound_timestamps.size() >= smart_notify_max_count) { shouldAdd = false; } } if (!shouldAdd) { notifyDisabled = true; } else { if (chat.sound_timestamps.size() >= smart_notify_max_count) chat.sound_timestamps.poll(); chat.sound_timestamps.add(currentDate); } } String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); if (!notifyDisabled) { inAppSounds = preferences.getBoolean("EnableInAppSounds", true); inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); inAppPreview = preferences.getBoolean("EnableInAppPreview", true); inAppPriority = preferences.getBoolean("EnableInAppPriority", false); vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); priority_override = preferences.getInt("priority_" + dialog_id, 3); choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); if (chat_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } needVibrate = preferences.getInt("vibrate_group", 0); priority = preferences.getInt("priority_group", 1); ledColor = preferences.getInt("GroupLed", 0xff00ff00); } else if (user_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } needVibrate = preferences.getInt("vibrate_messages", 0); priority = preferences.getInt("priority_group", 1); ledColor = preferences.getInt("MessagesLed", 0xff00ff00); } if (preferences.contains("color_" + dialog_id)) { ledColor = preferences.getInt("color_" + dialog_id, 0); } if (priority_override != 3) { priority = priority_override; } if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5) || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) { needVibrate = vibrate_override; } if (!ApplicationLoader.mainInterfacePaused) { if (!inAppSounds) { choosenSoundPath = null; } if (!inAppVibrate) { needVibrate = 2; } if (!inAppPriority) { priority = 0; } else if (priority == 2) { priority = 1; } } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if ((int) dialog_id != 0) { if (pushDialogs.size() == 1) { if (chat_id != 0) { intent.putExtra("chatId", chat_id); } else if (user_id != 0) { intent.putExtra("userId", user_id); } } if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { photoPath = null; } else { if (pushDialogs.size() == 1) { if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } } } else { if (pushDialogs.size() == 1) { intent.putExtra("encId", (int) (dialog_id >> 32)); } } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); String name = null; boolean replace = true; if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { name = LocaleController.getString("AppName", R.string.AppName); replace = false; } else { if (chat != null) { name = chat.title; } else { name = ContactsController.formatName(user.first_name, user.last_name); } } String detailText = null; if (pushDialogs.size() == 1) { detailText = LocaleController.formatPluralString("NewMessages", total_unread_count); } else { detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromChats", pushDialogs.size())); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setAutoCancel(true).setNumber(total_unread_count) .setContentIntent(contentIntent).setGroup("messages").setGroupSummary(true) //.setColor(0xff2ca5e0); .setColor(AndroidUtilities.getIntColor("themeColor")); if (priority == 0) { mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT); } else if (priority == 1) { mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); } else if (priority == 2) { mBuilder.setPriority(NotificationCompat.PRIORITY_MAX); } mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE); if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { mBuilder.addPerson("tel:+" + user.phone); } /*Bundle bundle = new Bundle(); bundle.putString(NotificationCompat.EXTRA_PEOPLE, ); mBuilder.setExtras()*/ String lastMessage = null; String lastMessageFull = null; if (pushMessages.size() == 1) { String message = lastMessageFull = getStringForMessage(pushMessages.get(0), false); //lastMessage = getStringForMessage(pushMessages.get(0), true); lastMessage = lastMessageFull; if (message == null) { return; } if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } mBuilder.setContentText(message); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } else { mBuilder.setContentText(detailText); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(name); int count = Math.min(10, pushMessages.size()); for (int i = 0; i < count; i++) { String message = getStringForMessage(pushMessages.get(i), false); if (message == null) { continue; } if (i == 0) { lastMessageFull = message; //lastMessage = getStringForMessage(pushMessages.get(i), true); lastMessage = lastMessageFull; } if (pushDialogs.size() == 1) { if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } } inboxStyle.addLine(message); } inboxStyle.setSummaryText(detailText); mBuilder.setStyle(inboxStyle); } if (photoPath != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50"); if (img != null) { mBuilder.setLargeIcon(img.getBitmap()); } } if (!notifyDisabled) { if (ApplicationLoader.mainInterfacePaused || inAppPreview) { if (lastMessage.length() > 100) { lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "..."; } mBuilder.setTicker(lastMessage); } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (choosenSoundPath.equals(defaultPath)) { /*MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI); mediaPlayer.prepare(); mediaPlayer.start();*/ mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); } else { mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); } } if (ledColor != 0) { mBuilder.setLights(ledColor, 1000, 1000); } if (needVibrate == 2) { mBuilder.setVibrate(new long[] { 0, 0 }); } else if (needVibrate == 1) { mBuilder.setVibrate(new long[] { 0, 100, 0, 100 }); } else if (needVibrate == 0 || needVibrate == 4) { mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE); } else if (needVibrate == 3) { mBuilder.setVibrate(new long[] { 0, 1000 }); } } else { mBuilder.setVibrate(new long[] { 0, 0 }); } notificationManager.notify(1, mBuilder.build()); if (preferences.getBoolean("EnablePebbleNotifications", false)) { sendAlertToPebble(lastMessageFull); } showWearNotifications(notifyAboutLast); scheduleNotificationRepeat(); } catch (Exception e) { FileLog.e("tmessages", e); } }
From source file:br.com.Utilitarios.WorkUpService.java
public void criarNotificacoes(Notificacoes n, String titulo, String texto, String ticker, String tipo, String extra) {//w w w .j a v a 2 s .c o m // Build notification NotificationCompat.Builder noti = new NotificationCompat.Builder(this); noti.setContentTitle(titulo); noti.setContentText(texto); noti.setTicker(ticker); noti.setSmallIcon(R.drawable.ic_launcher); Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); noti.setSound(alarmSound); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent resultIntent = null; if (tipo.equals("novoPersonal")) { // Creates an expnovaAvaliacaolicit intent for an Activity in your app resultIntent = new Intent(this, AceitarRejeitarAmigo.class); resultIntent.putExtra("usuario", n.getOrigemNotificacao()); resultIntent.putExtra("tipo", "aluno"); } if (tipo.equals("novoAluno")) { resultIntent = new Intent(this, AceitarRejeitarAmigo.class); resultIntent.putExtra("usuario", n.getOrigemNotificacao()); resultIntent.putExtra("tipo", "personal"); } if (tipo.equals("novaAula")) { // Creates an explicit intent for an Activity in your app resultIntent = new Intent(this, ConfirmarAula.class); resultIntent.putExtra("codAula", extra); } //This ensures that navigating backward from the Activity leads out of the app to Home page TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); if (tipo.equals("novoPersonal") || tipo.equals("novoAluno")) { // Adds the back stack for the Intent stackBuilder.addParentStack(AceitarRejeitarAmigo.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT //can only be used once ); // start the activity when the user clicks the notification text noti.setContentIntent(resultPendingIntent); } // pass the Notification object to the system notificationManager.notify(0, noti.build()); n.visualizarNotificacao(n.getCodNotificacao()); //---------------------------------------------------------------------------------- }
From source file:com.digitalarx.android.files.services.FileUploader.java
/** * Updates the status notification with the result of an upload operation. * /*from w w w .j av a 2s. com*/ * @param uploadResult Result of the upload operation. * @param upload Finished upload operation */ private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) { Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode()); // / cancelled operation or success -> silent removal of progress notification mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker); // Show the result: success or fail notification if (!uploadResult.isCancelled()) { int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker : R.string.uploader_upload_failed_ticker; NotificationCompat.Builder resultBuilder = new NotificationCompat.Builder(this); String content = null; // check credentials error boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED || uploadResult.isIdPRedirection()); tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId; resultBuilder.setSmallIcon(R.drawable.notification_icon).setTicker(getString(tickerId)) .setContentTitle(getString(tickerId)).setAutoCancel(true); content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources()); if (needsToUpdateCredentials) { // let the user update credentials with one click Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND); resultBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT)); mUploadClient = null; // grant that future retries on the same account will get the fresh credentials } else { // TODO put something smart in the contentIntent below // we add only for instant-uploads the InstantUploadActivity and the // db entry Intent detailUploadIntent = new Intent(this, InstantUploadActivity.class); detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount()); resultBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT)) .setContentText(content); if (upload.isInstant()) { DbHandler db = null; try { db = new DbHandler(this.getBaseContext()); String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode(); Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode()); if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) { message = getString(R.string.failed_upload_quota_exceeded_text); if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED, message) == 0) { db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message); } } } finally { if (db != null) { db.close(); } } } } resultBuilder.setContentText(content); mNotificationManager.notify(tickerId, resultBuilder.build()); if (uploadResult.isSuccess()) { DbHandler db = new DbHandler(this.getBaseContext()); db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath()); db.close(); // remove success notification, with a delay of 2 seconds NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker, 2000); } } }