List of usage examples for android.app PendingIntent getBroadcast
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags)
From source file:com.mobilyzer.MeasurementScheduler.java
public synchronized String submitTask(MeasurementTask newTask) { // TODO check if scheduler is running... // and there is a current running/scheduled task String newTaskId = newTask.getTaskId(); tasksStatus.put(newTaskId, TaskStatus.SCHEDULED); idToClientKey.put(newTaskId, newTask.getKey()); Logger.d("MeasurementScheduler --> submitTask: " + newTask.getDescription().key + " " + newTaskId); MeasurementTask current;/*from w ww .j a v a 2s. c o m*/ if (getCurrentTask() != null) { current = getCurrentTask(); Logger.d("submitTask: current is NOT null"); } else { current = null; Logger.d("submitTask: current is null"); } // preemption condition if (current != null && newTask.getDescription().priority < current.getDescription().priority && new Date(current.getDuration() + getCurrentTaskStartTime().getTime()) .after(newTask.getDescription().endTime)) { Logger.d("submitTask: trying to cancel/preempt the task"); // finding the current instance in pending tasks. we can call // pause on that instance only if (pendingTasks.containsKey(current)) { for (MeasurementTask mt : pendingTasks.keySet()) { if (current.equals(mt)) { current = mt; break; } } Logger.e("Cancelling Current Task"); if (current instanceof PreemptibleMeasurementTask && ((PreemptibleMeasurementTask) current).pause()) { pendingTasks.remove(current); ((PreemptibleMeasurementTask) current).updateTotalRunningTime( System.currentTimeMillis() - getCurrentTaskStartTime().getTime()); if (newTask.timeFromExecution() <= 0) { mainQueue.add(newTask); mainQueue.add(current); handleMeasurement(); } else { mainQueue.add(newTask); mainQueue.add(current); long timeFromExecution = newTask.timeFromExecution(); measurementIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution, measurementIntentSender); setCurrentTask(newTask); setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution)); } } else if (current.stop()) { pendingTasks.remove(current); if (newTask.timeFromExecution() <= 0) { mainQueue.add(newTask); mainQueue.add(current); handleMeasurement(); } else { mainQueue.add(newTask); mainQueue.add(current); long timeFromExecution = newTask.timeFromExecution(); measurementIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution, measurementIntentSender); // setCurrentTask(null); setCurrentTask(newTask); setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution)); } } else { mainQueue.add(newTask); } } else { alarmManager.cancel(measurementIntentSender); if (newTask.timeFromExecution() <= 0) { mainQueue.add(newTask); handleMeasurement(); } else { mainQueue.add(newTask); long timeFromExecution = newTask.timeFromExecution(); measurementIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution, measurementIntentSender); // setCurrentTask(null); setCurrentTask(newTask); setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution)); } } } else { Logger.d("submitTask: adding to mainqueue"); mainQueue.add(newTask); if (current == null) { Logger.d("submitTask: adding to mainqueue, current is null"); Logger.d("submitTask: calling handleMeasurement"); alarmManager.cancel(measurementIntentSender); handleMeasurement(); } else { Logger.d("submitTask: adding to mainqueue, current is not null: " + current.getMeasurementType() + " " + getCurrentTaskStartTime()); if (pendingTasks.containsKey(current)) { Logger.d("submitTask: isDone?" + pendingTasks.get(current).isDone()); if (pendingTasks.get(current).isDone()) { alarmManager.cancel(measurementIntentSender); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 1000, measurementIntentSender); } else if (getCurrentTaskStartTime() != null) { if (!current.getMeasurementType().equals(RRCTask.TYPE) && new Date(System.currentTimeMillis() - Config.MAX_TASK_DURATION) .after(getCurrentTaskStartTime())) { Logger.d("submitTask: 1"); pendingTasks.get(current).cancel(true); handleMeasurement(); } else if (current.getMeasurementType().equals(RRCTask.TYPE) && new Date( System.currentTimeMillis() - (Config.DEFAULT_RRC_TASK_DURATION + 15 * 60 * 1000)) .after(getCurrentTaskStartTime())) { Logger.d("submitTask: 2"); pendingTasks.get(current).cancel(true); handleMeasurement(); } else { Logger.d("submitTask: 3"); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + Config.MAX_TASK_DURATION / 2, measurementIntentSender); } } } else { Logger.d("submitTask: not found in pending task"); handleMeasurement(); } } } return newTaskId; }
From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java
private void c2dmRegister(Context context, String senderId) { Log.d(TAG, "c2dmRegister: context=" + context + ", senderId=" + senderId); Intent intent = new Intent(REQUEST_REGISTRATION_INTENT); intent.setPackage(GSF_PACKAGE);// ww w .j a v a2 s .co m intent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); intent.putExtra(EXTRA_SENDER, senderId); ComponentName name = context.startService(intent); if (name == null) { // Service not found. setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_C2DM_NOT_FOUND); } }
From source file:com.irccloud.android.data.collection.NotificationsList.java
@SuppressLint("NewApi") private android.app.Notification buildNotification(String ticker, int cid, int bid, long[] eids, String title, String text, int count, Intent replyIntent, String network, ArrayList<Notification> messages, NotificationCompat.Action otherAction, Bitmap largeIcon, Bitmap wearBackground) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel c = new NotificationChannel(String.valueOf(bid), title, NotificationManager.IMPORTANCE_HIGH); c.setGroup(String.valueOf(cid)); ((NotificationManager) IRCCloudApplication.getInstance().getApplicationContext() .getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(c); }/*ww w . j a v a2s. com*/ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()); int defaults = 0; NotificationCompat.Builder builder = new NotificationCompat.Builder( IRCCloudApplication.getInstance().getApplicationContext(), String.valueOf(bid)) .setContentTitle( title + ((network != null && !network.equals(title)) ? (" (" + network + ")") : "")) .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker) .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify).setLargeIcon(largeIcon) .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources() .getColor(R.color.ic_background)) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setPriority(hasTouchWiz() ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_HIGH) .setOnlyAlertOnce(false); if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000) { String ringtone = prefs.getString("notify_ringtone", "android.resource://" + IRCCloudApplication.getInstance().getApplicationContext().getPackageName() + "/" + R.raw.digit); if (ringtone.length() > 0) builder.setSound(Uri.parse(ringtone)); } int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1")); if (led_color == 1) { defaults = android.app.Notification.DEFAULT_LIGHTS; } else if (led_color == 2) { builder.setLights(0xFF0000FF, 500, 500); } if (prefs.getBoolean("notify_vibrate", true) && ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000) defaults |= android.app.Notification.DEFAULT_VIBRATE; else builder.setVibrate(new long[] { 0L }); builder.setDefaults(defaults); 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); WearableExtender wearableExtender = new WearableExtender(); wearableExtender.setBackground(wearBackground); if (messages != null && messages.size() > 0) { StringBuilder weartext = new StringBuilder(); String servernick = getServerNick(messages.get(0).cid); NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(servernick); style.setConversationTitle(title + ((network != null) ? (" (" + network + ")") : "")); for (Notification n : messages) { if (n != null && n.message != null && n.message.length() > 0) { if (weartext.length() > 0) weartext.append("<br/>"); if (n.message_type.equals("buffer_me_msg")) { style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000, " " + ((n.nick == null) ? servernick : n.nick)); weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick).append("</b> ") .append(n.message); } else { style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000, n.nick); weartext.append("<b><").append((n.nick == null) ? servernick : n.nick) .append("></b> ").append(n.message); } } } ArrayList<String> history = new ArrayList<>(messages.size()); for (int j = messages.size() - 1; j >= 0; j--) { Notification n = messages.get(j); if (n != null) { if (n.nick == null) history.add(Html.fromHtml(n.message).toString()); else break; } } builder.setRemoteInputHistory(history.toArray(new String[history.size()])); builder.setStyle(style); if (messages.size() > 1) { wearableExtender.addPage( new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext()) .setContentText(Html.fromHtml(weartext.toString())) .extend(new WearableExtender().setStartScrollBottom(true)).build()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { weartext.setLength(0); int j = 0; for (Notification n : messages) { if (messages.size() - ++j < 3) { if (n != null && n.message != null && n.message.length() > 0) { if (weartext.length() > 0) weartext.append("<br/>"); if (n.message_type.equals("buffer_me_msg")) { weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick) .append("</b> ").append(n.message); } else { weartext.append("<b><").append((n.nick == null) ? servernick : n.nick) .append("></b> ").append(n.message); } } } } 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, Html.fromHtml(weartext.toString())); bigContentView.setImageViewBitmap(R.id.image, largeIcon); 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); } builder.setCustomBigContentView(bigContentView); } } if (replyIntent != null) { PendingIntent replyPendingIntent = PendingIntent.getService( IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { builder.addAction(new NotificationCompat.Action.Builder(0, "Reply", replyPendingIntent) .setAllowGeneratedReplies(true) .addRemoteInput( new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()) .build()); } NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder( R.drawable.ic_wearable_reply, "Reply", replyPendingIntent).setAllowGeneratedReplies(true) .addRemoteInput( new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()); NotificationCompat.Action.WearableExtender actionExtender = new NotificationCompat.Action.WearableExtender() .setHintLaunchesActivity(true).setHintDisplayActionInline(true); wearableExtender.addAction(actionBuilder.extend(actionExtender).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 (messages != null) { for (Notification n : messages) { if (n != null && n.nick != null && n.message != null && n.message.length() > 0) { if (n.buffer_type.equals("conversation")) { if (n.message_type.equals("buffer_me_msg")) unreadConvBuilder .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString()); else unreadConvBuilder.addMessage(Html.fromHtml(n.message).toString()); } else { if (n.message_type.equals("buffer_me_msg")) unreadConvBuilder .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString()); else unreadConvBuilder .addMessage(n.nick + " said: " + Html.fromHtml(n.message).toString()); } } } } else { unreadConvBuilder.addMessage(text); } unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000); builder.extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build())); } if (replyIntent != null && prefs.getBoolean("notify_quickreply", true) && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { 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); } if (otherAction != null) { int drawable = 0; if (otherAction.getIcon() == R.drawable.ic_wearable_add) drawable = R.drawable.ic_action_add; else if (otherAction.getIcon() == R.drawable.ic_wearable_reply) drawable = R.drawable.ic_action_reply; builder.addAction( new NotificationCompat.Action(drawable, otherAction.getTitle(), otherAction.getActionIntent())); wearableExtender.addAction(otherAction); } builder.extend(wearableExtender); return builder.build(); }
From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java
private void c2dmUnregister(Context context) { Log.d(TAG, "c2dmUnregister: context=" + context); Intent intent = new Intent(REQUEST_UNREGISTRATION_INTENT); intent.setPackage(GSF_PACKAGE);//w w w. j av a 2 s . c om intent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); ComponentName name = context.startService(intent); if (name == null) { // Service not found. setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_C2DM_NOT_FOUND); } }
From source file:com.daiv.android.twitter.utils.NotificationUtils.java
public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) { String shortText;//ww w . ja v a2s . c o m String longText; String title; int smallIcon = R.drawable.ic_stat_icon; Bitmap largeIcon; PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, null, 0); NotificationCompat.InboxStyle inbox = null; if (tweets.size() == 1) { title = tweets.get(0)[0]; shortText = tweets.get(0)[1]; longText = shortText; largeIcon = getImage(context, tweets.get(0)[2]); } else { inbox = new NotificationCompat.InboxStyle(); title = context.getResources().getString(R.string.favorite_users); shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets); longText = ""; try { inbox.setBigContentTitle(shortText); } catch (Exception e) { } if (tweets.size() <= 5) { for (String[] s : tweets) { inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1])); } } else { for (int i = 0; i < 5; i++) { inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1])); } inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets)); } largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark); } NotificationCompat.Builder mBuilder; AppSettings settings = AppSettings.getInstance(context); if (shortText.contains("@" + settings.myScreenName)) { // return because there is a mention notification for this already return; } Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class); mBuilder = new NotificationCompat.Builder(context).setContentTitle(title) .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon) .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)) .setPriority(NotificationCompat.PRIORITY_HIGH); if (inbox == null) { mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml( settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText))); } else { mBuilder.setStyle(inbox); } 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.notifications) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(2, mBuilder.build()); // if we want to wake the screen on a new message 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 (context .getSharedPreferences("com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE) .getBoolean("pebble_notification", false)) { sendAlertToPebble(context, title, shortText); } // Light Flow notification sendToLightFlow(context, title, shortText); } }
From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java
private void showUpdateNotification() { Log.d(TAG, "showUpdateNotification: " + getKeyboardString()); // Intent for triggering the update confirmation page. Intent updateConfirmation = new Intent(this, UpdateConfirmationActivity.class); updateConfirmation.putExtra(EXTRA_KEYBOARD_NAME, mKeyboardName); updateConfirmation.putExtra(EXTRA_KEYBOARD_ADDRESS, mKeyboardAddress); updateConfirmation.putExtra(EXTRA_KEYBOARD_FIRMWARE_VERSION, mKeyboardFirmwareVersion); updateConfirmation.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Intent for postponing update. Intent postponeUpdate = new Intent(ACTION_KEYBOARD_UPDATE_POSTPONED); // Wrap intents into pending intents for notification use. PendingIntent laterIntent = PendingIntent.getBroadcast(this, 0, postponeUpdate, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent installIntent = PendingIntent.getActivity(this, 0, updateConfirmation, PendingIntent.FLAG_CANCEL_CURRENT); // Create a notification object with two buttons (actions) mUpdateNotification = new NotificationCompat.Builder(this).setCategory(Notification.CATEGORY_SYSTEM) .setContentTitle(getString(R.string.notification_update_title)) .setContentText(getString(R.string.notification_update_text)).setSmallIcon(R.drawable.ic_keyboard) .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_later, getString(R.string.notification_update_later), laterIntent).build()) .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_install, getString(R.string.notification_update_install), installIntent).build()) .setAutoCancel(true).setOnlyAlertOnce(true).build(); // Show the notification via notification manager NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notificationManager.notify(UPDATE_NOTIFICATION_ID, mUpdateNotification); }
From source file:com.heightechllc.breakify.MainActivity.java
/** * Cancels the alarm scheduled by startTimer() *///from www .j av a2s.c om private void cancelScheduledAlarm() { // Cancel the AlarmManager PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ALARM_MANAGER_REQUEST_CODE, new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.cancel(pendingIntent); // Hide the persistent notification AlarmNotifications.hideNotification(this); // Remove record of when the timer will ring sharedPref.edit().remove("schedRingTime").apply(); }
From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java
private void c2dmHandleRegistrationResponse(final Context context, Intent intent) { Log.d(TAG, "c2dmHandleRegistrationResponse: context=" + context + ", intent=" + intent + ", extras=" + Utils.bundleToString(intent.getExtras())); final String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); mConfiguration.putLong(LAST_CHANGE, System.currentTimeMillis()); if (unregistered != null) { // Unregistered mConfiguration.putString(REG_ID, ""); setStateAndNotify(REGISTRATION_STATE_UNREGISTERING, REGISTRATION_SUBSTATE_NONE); mHandler.sendEmptyMessage(EVENT_UNREGISTER_COMPLETE); } else if (error != null) { // Registration failed. Log.e(TAG, "Registration error " + error); mConfiguration.putString(REG_ID, ""); setStateAndNotify(REGISTRATION_STATE_ERROR, error); if ("SERVICE_NOT_AVAILABLE".equals(error)) { long backoffTime = mConfiguration.getLong(C2DM_BACKOFF, DEFAULT_BACKOFF); // For this error, try again later. Log.d(TAG, "Scheduling registration retry, backoff = " + backoffTime); Intent retryIntent = new Intent(C2DM_INTENT_RETRY); PendingIntent retryPIntent = PendingIntent.getBroadcast(context, 0 /* requestCode */, retryIntent, 0 /* flags */); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, backoffTime, retryPIntent); // Next retry should wait longer. backoffTime *= BACKOFF_MULTIPLIER; if (backoffTime > MAX_BACKOFF) { backoffTime = MAX_BACKOFF; mConfiguration.putLong(C2DM_BACKOFF, backoffTime); }//from w w w . ja va 2 s . c o m // Save the backoff time. writePreferences(); } } else { mConfiguration.putString(REG_ID, registrationId); setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_HAVE_REG_ID); mHandler.sendEmptyMessage(EVENT_REGISTER_COMPLETE); } }
From source file:com.dzt.musicplay.player.AudioService.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void showNotification() { Constant.print_i("AudioService----------->showNotification"); try {//w w w. j a v a 2 s.c o m Media media = getCurrentMedia(); if (media == null) return; Bitmap cover = AudioUtil.getCover(this, media, 64); String title = media.getTitle(); String artist = media.getArtist(); String album = media.getAlbum(); Notification notification; // add notification to status bar NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon_music).setTicker(title + " - " + artist).setAutoCancel(false) .setOngoing(true); //Activity Intent notificationIntent = new Intent(this, MusicPlayActivity.class); notificationIntent.setAction(MusicPlayActivity.ACTION_SHOW_PLAYER); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); notificationIntent.putExtra(START_FROM_NOTIFICATION, true); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (LibVlcUtil.isJellyBeanOrLater()) { Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD); Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE); Intent iForward = new Intent(ACTION_REMOTE_FORWARD); Intent iStop = new Intent(ACTION_REMOTE_STOP); PendingIntent piBackward = PendingIntent.getBroadcast(this, 0, iBackward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piPlay = PendingIntent.getBroadcast(this, 0, iPlay, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piForward = PendingIntent.getBroadcast(this, 0, iForward, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent piStop = PendingIntent.getBroadcast(this, 0, iStop, PendingIntent.FLAG_UPDATE_CURRENT); RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification); if (cover != null) view.setImageViewBitmap(R.id.cover, cover); view.setTextViewText(R.id.songName, title); view.setTextViewText(R.id.artist, artist); view.setImageViewResource(R.id.play_pause, mLibVLC.isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w); view.setOnClickPendingIntent(R.id.play_pause, piPlay); view.setOnClickPendingIntent(R.id.forward, piForward); view.setOnClickPendingIntent(R.id.stop, piStop); view.setOnClickPendingIntent(R.id.content, pendingIntent); RemoteViews view_expanded = new RemoteViews(getPackageName(), R.layout.notification_expanded); if (cover != null) view_expanded.setImageViewBitmap(R.id.cover, cover); view_expanded.setTextViewText(R.id.songName, title); view_expanded.setTextViewText(R.id.artist, artist); view_expanded.setTextViewText(R.id.album, album); view_expanded.setImageViewResource(R.id.play_pause, mLibVLC.isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w); view_expanded.setOnClickPendingIntent(R.id.backward, piBackward); view_expanded.setOnClickPendingIntent(R.id.play_pause, piPlay); view_expanded.setOnClickPendingIntent(R.id.forward, piForward); view_expanded.setOnClickPendingIntent(R.id.stop, piStop); view_expanded.setOnClickPendingIntent(R.id.content, pendingIntent); notification = builder.build(); notification.contentView = view; notification.bigContentView = view_expanded; } else { builder.setLargeIcon(cover).setContentTitle(title) .setContentText(LibVlcUtil.isJellyBeanOrLater() ? artist : media.getSubtitle()) .setContentInfo(album).setContentIntent(pendingIntent); notification = builder.build(); } startService(new Intent(this, AudioService.class)); startForeground(3, notification); } catch (NoSuchMethodError e) { // Compat library is wrong on 3.2 // http://code.google.com/p/android/issues/detail?id=36359 // http://code.google.com/p/android/issues/detail?id=36502 } Constant.print_i("AudioService----------->showNotification----end"); }
From source file:com.klinker.android.twitter.utils.NotificationUtils.java
public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) { String shortText;/*ww w .j a v a2s . c o m*/ String longText; String title; int smallIcon = R.drawable.ic_stat_icon; Bitmap largeIcon; Intent resultIntent; if (toDrawer) { resultIntent = new Intent(context, RedirectToDrawer.class); } else { resultIntent = new Intent(context, NotiTweetPager.class); } PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0); NotificationCompat.InboxStyle inbox = null; if (tweets.size() == 1) { title = tweets.get(0)[0]; shortText = tweets.get(0)[1]; longText = shortText; largeIcon = getImage(context, tweets.get(0)[2]); } else { inbox = new NotificationCompat.InboxStyle(); title = context.getResources().getString(R.string.favorite_users); shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets); longText = ""; try { inbox.setBigContentTitle(shortText); } catch (Exception e) { } if (tweets.size() <= 5) { for (String[] s : tweets) { inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1])); } } else { for (int i = 0; i < 5; i++) { inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1])); } inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets)); } largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark); } NotificationCompat.Builder mBuilder; AppSettings settings = AppSettings.getInstance(context); if (shortText.contains("@" + settings.myScreenName)) { // return because there is a mention notification for this already return; } Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class); mBuilder = new NotificationCompat.Builder(context).setContentTitle(title) .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon) .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)) .setPriority(NotificationCompat.PRIORITY_HIGH); if (inbox == null) { mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml( settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText))); } else { mBuilder.setStyle(inbox); } 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.notifications) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(2, mBuilder.build()); // if we want to wake the screen on a new message 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 (context .getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE) .getBoolean("pebble_notification", false)) { sendAlertToPebble(context, title, shortText); } // Light Flow notification sendToLightFlow(context, title, shortText); } }