public void updateTicker(String text) { Log.v(this.toString(), "Updating ticker with " + text); notificationBuilder.setTicker(text + ((this.even = this.even ? false : true) ? " " : "")); notificationBuilder.setSmallIcon(R.drawable.ic_notification); this.notificationManager.notify(Defaults.NOTIFCATION_ID, notificationBuilder.build()); // Clear ticker notificationBuilder.setTicker(null); this.notificationManager.notify(Defaults.NOTIFCATION_ID, notificationBuilder.build()); // if the notification is not enabled, the ticker will create an empty // one that we get rid of if (!Preferences.isNotificationEnabled()) this.notificationManager.cancel(Defaults.NOTIFCATION_ID); }
/** * 开始更新 * * @param context 当前上下文 * @param url 下载地址 */ public void startUpdate(Context context, String url) { isCancel = false; apkName = getApkName(url); // 新建文件夹 File fp = new File(save_path); if (!fp.exists()) { fp.mkdir(); } mNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE); // 初始化通知栏 mBuilder = new NotificationCompat.Builder(context); mBuilder .setTicker("开始下载更新") .setSmallIcon(mUpdatingIconId) .setContentIntent( getDefalutIntent(context, Notification.FLAG_NO_CLEAR | PendingIntent.FLAG_ONE_SHOT)) .setDefaults(Notification.DEFAULT_SOUND) .setContentTitle("更新") .setPriority(Notification.PRIORITY_DEFAULT) .setOngoing(true); // 设置通知小ICON Notification notification = mBuilder.build(); mNotificationManager.notify(1, notification); // 启动下载服务 Intent service = new Intent(context, UpdateService.class); service.putExtra("url", url); context.startService(service); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent i = new Intent(getIntent()); nome = i.getIntExtra("nome", nome); foto = i.getIntExtra("foto", foto); id = UUID.fromString(i.getStringExtra("id")); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(getString(R.string.novo_evento)); builder.setContentText(getString(nome)); builder.setTicker(getString(R.string.notificacao_evento)); builder.setSmallIcon(foto); // TODO colocar rodar mesmo com app fechado Intent resultIntent = new Intent(this, EventoPagerActivity.class); resultIntent.putExtra(EventoFragment.EXTRA_EVENTO_ID, id); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT); builder.setContentIntent(resultPendingIntent); builder.setAutoCancel(true); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(idNotificacao, builder.build()); finish(); }
@Override public void onReceive(Context context, Intent i) { Log.d("alarm", "alarm ring! ring!"); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder mCompatBuilder = new NotificationCompat.Builder(context); switch (i.getIntExtra("sound", 0)) { case 0: if ("ON".equals(SharedPreferenceManager.getInstance().getSound())) { mCompatBuilder.setDefaults(Notification.DEFAULT_SOUND); } else { mCompatBuilder.setDefaults(Notification.DEFAULT_LIGHTS); } break; case 1: if ("ON".equals(SharedPreferenceManager.getInstance().getVibration())) { mCompatBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } else { mCompatBuilder.setDefaults(Notification.DEFAULT_LIGHTS); } break; case 2: mCompatBuilder.setDefaults(Notification.DEFAULT_LIGHTS); break; } mCompatBuilder.setSmallIcon(R.drawable.ic_launcher); mCompatBuilder.setTicker(i.getStringExtra("ticker")); mCompatBuilder.setContentTitle(i.getStringExtra("title")); mCompatBuilder.setContentText(i.getStringExtra("text")); mCompatBuilder.setAutoCancel(true); nm.notify(0, mCompatBuilder.build()); }
// 发送简单通知 private NotificationCompat.Builder sendSimpleNotification(NotificationCompat.Builder builder) { builder.setTicker("通知来了"); builder.setContentTitle("新消息"); builder.setContentText("要放假了"); return builder; }
/** * 当应用在前台时,如果当前消息不是属于当前会话,在状态栏提示一下 如果不需要,注释掉即可 * * @param message */ protected void notifyNewMessage(EMMessage message, String nick) { // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的,demo里不做判断) // 以及设置了setShowNotificationInbackgroup:false(设为false后,后台时sdk也发送广播) if (!EasyUtils.isAppRunningForeground(this)) { return; } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(false); String ticker = CommonUtils.getMessageDigest(message, this); String st = getResources().getString(R.string.expression); if (message.getType() == EMMessage.Type.TXT) ticker = ticker.replaceAll("\\[.{2,3}\\]", st); // 设置状态栏提示 mBuilder.setTicker(nick + ": " + ticker); mBuilder.setContentText("查看新的未读消息"); mBuilder.setContentTitle(message.getStringAttribute(Const.Easemob.FROM_USER_NICK, "新消息")); // 必须设置pendingintent,否则在2.3的机器上会有bug Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Const.Intent.HX_NTF_TO_MAIN, true); PendingIntent pendingIntent = PendingIntent.getActivity(this, notifiId, intent, PendingIntent.FLAG_ONE_SHOT); mBuilder.setContentIntent(pendingIntent); Notification notification = mBuilder.build(); notificationManager.notify(notifiId, notification); // notificationManager.cancel(notifiId); }
@Override public void onClick(View v) { // TODO Auto-generated method stub NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World! \n hello world!!"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, MainController.class); // The stack builder object will contain an artificial back stack // for the // started Activity. // This ensures that navigating backward from the Activity leads out // of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainController.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mBuilder.setTicker("helo"); mNotificationManager.notify(1, mBuilder.build()); mBuilder.setNumber(1).setAutoCancel(true); }
@Override public void vshow( final Context context, final String message, final String tickerText, final int id, PendingIntent contentIntent) { /* * If contentIntent is NULL, create valid contentIntent */ if (contentIntent == null) contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setTicker(tickerText); builder.setWhen(System.currentTimeMillis()); builder.setSmallIcon(R.drawable.icon); builder.setContentTitle(context.getText(R.string.app_name)); builder.setContentIntent(contentIntent); builder.setContentText(message); builder.setAutoCancel(true); // unique ID notify(context, id, VSHOW_TAG, builder.build()); }
public void showChatNotification() { if (unreadMessages.size() == 0) return; Message lastMessage = unreadMessages.get(unreadMessages.size() - 1); mStatusNotificationBuilder.setTicker( ((lastMessage.actor != null && lastMessage.actor.name != null) ? lastMessage.actor.name : getString(R.string.server)) + ": " + Html.fromHtml(lastMessage.message).toString()); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Message message : unreadMessages) { inboxStyle.addLine( ((message.actor != null && message.actor.name != null) ? message.actor.name : getString(R.string.server)) + ": " + Html.fromHtml(message.message).toString()); // Escapes // HTML } mStatusNotificationBuilder.setStyle(inboxStyle); Notification notificationCompat = mStatusNotificationBuilder.build(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(STATUS_NOTIFICATION_ID, notificationCompat); }
/** * 当应用在前台时,如果当前消息不是属于当前会话,在状态栏提示一下 如果不需要,注释掉即可 * * @param message */ public void notifyNewMessage(EMMessage message) { // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的,demo里不做判断) // 以及设置了setShowNotificationInbackgroup:false(设为false后,后台时sdk也发送广播) if (!EasyUtils.isAppRunningForeground(this)) { return; } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.zhxy_logo) .setContentTitle("新消息") .setWhen(System.currentTimeMillis()) .setAutoCancel(true); String ticker = CommonUtils.getMessageDigest(message, this); String st = getResources().getString(R.string.expression); if (message.getType() == Type.TXT) ticker = ticker.replaceAll("\\[.{2,3}\\]", st); // 设置状态栏提示 mBuilder.setTicker(message.getFrom() + ": " + ticker); // 必须设置pendingintent,否则在2.3的机器上会有bug Intent intent = new Intent(this, ChatActivity.class); // 程序内 跳转 单聊 if (message.getChatType() == ChatType.Chat) { intent.putExtra(Constants.TEL, message.getFrom()); intent.putExtra(Constants.USNAME, message.getUserName()); Log.e("TAG", "收到的手机号 = " + message.getFrom()); Log.e("得到的用户名为:", message.getUserName()); } // 程序内 跳转 群聊 if (message.getChatType() == ChatType.GroupChat) { intent.putExtra(Constants.TEL, message.getTo()); intent.putExtra("chatType", Constants.CHATTYPE_GROUP); intent.putExtra( Constants.CLASS_SHORT_NAME, SharedPreferencesUtil.getClassShortName(getApplicationContext())); Log.e( "TAG", "收到的群组id = " + message.getTo() + "传递的 班级名称 = " + SharedPreferencesUtil.getClassShortName(getApplicationContext())); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, notifiId, intent, PendingIntent.FLAG_ONE_SHOT); mBuilder.setContentIntent(pendingIntent); Notification notification = mBuilder.build(); notificationManager.notify(notifiId, notification); Intent intent2 = new Intent(); intent2.setAction(Constants.AREA_UNREAD); intent2.putExtra(Constants.MSG_FROM, message.getFrom()); sendOrderedBroadcast(intent2, null); }
/** * @param ID データベースのID * @param title Notificationで表示されるタイトル * @param subTitle Notificationで表示されるサブタイトル * @param message Notificationが生成された時に表示されるステータスメッセージ * @param color メモ画面での色 * @param content メモ画面の中身 * @param photoPath カメラ撮影時の画像ファイルパス * @param drawingPath 手書きの画像ファイルパス * @param voicePath 音声ファイルパス */ private void setToDoDetailNotification( int ID, String title, String subTitle, String message, int color, String content, String photoPath, String drawingPath, String voicePath) { // Intentの作成 // ※ 要変更:現在はスタブクラスにインテントを渡しているが、これを本来のMemo画面クラスに渡す Intent intent = new Intent(SetToDoNotification.this, StubMemoActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // サービスからインテントを使用するためにフラグを設定 // Memo画面に必要な情報をインテントに格納する intent.putExtra("Color", color); intent.putExtra("Content", content); intent.putExtra("PhotoPath", photoPath); intent.putExtra("DrawingPath", drawingPath); intent.putExtra("VoicePath", voicePath); PendingIntent contentIntent = PendingIntent.getActivity( SetToDoNotification.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // NotificationBuilderを作成 NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); // Intentを埋め込む builder.setContentIntent(contentIntent); // ステータスバーに表示されるテキスト builder.setTicker(message); // アイコン builder.setSmallIcon(android.R.drawable.ic_menu_today); // Notificationを開いた時に表示されるタイトル builder.setContentTitle(title); // Notificationを開いた時に表示されるサブタイトル builder.setContentText(subTitle); // Notificationを開いた時に表示されるアイコン // builder.setLargeIcon(largeIcon); // 通知するタイミング builder.setWhen(System.currentTimeMillis()); // 通知時の音・ライト builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS); // タップするとキャンセル(消える) builder.setAutoCancel(true); // NotificationManagerを取得 NotificationManager manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); // Notificationを作成して通知 manager.notify(ID, builder.build()); }
public void clearChatNotification() { if (unreadMessages == null || mStatusNotificationBuilder == null) return; unreadMessages.clear(); mStatusNotificationBuilder.setTicker(null); mStatusNotificationBuilder.setStyle(null); Notification notificationCompat = mStatusNotificationBuilder.build(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(STATUS_NOTIFICATION_ID, notificationCompat); }
public void show() { builder.setContentTitle(title()); builder.setContentText(contentText()); builder.setSmallIcon(smallIcon()); builder.setTicker(contentText()); builder.setAutoCancel(true); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Notification notification = builder.build(); // notification.flags = Notification.FLAG_AUTO_CANCEL; // notification.defaults = Notification.DEFAULT_ALL; manager.notify(id, builder.build()); }
/** * this is to display the limit excess message to user as notification * * @param message */ public void displayMessage(String message) { // TODO Auto-generated method stub Log.i("Testing", "In display function"); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Month shopping limit") .setContentText(message); Intent notificationIntent = new Intent(this, StartActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(contentIntent); builder.setAutoCancel(true); builder.setTicker(message); messagesManager.notify(NOTI_NO, builder.build()); Log.i("Testing", "In display function after set notify"); }
public void sendNotification(String message, boolean isForeground) { Context appContext = HXSDKHelper.getInstance().getAppContext(); if (notificationManager == null) { notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE); } try { String notifyText = message; PackageManager packageManager = appContext.getPackageManager(); String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo()); // notification titile String contentTitle = appname; String packageName = appContext.getApplicationInfo().packageName; Uri defaultSoundUrlUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // create and send notificaiton NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext) .setSmallIcon(appContext.getApplicationInfo().icon) .setSound(defaultSoundUrlUri) .setWhen(System.currentTimeMillis()) .setAutoCancel(true); Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName); PendingIntent pendingIntent = PendingIntent.getActivity( appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentTitle(contentTitle); mBuilder.setTicker(notifyText); mBuilder.setContentText(notifyText); mBuilder.setContentIntent(pendingIntent); Notification notification = mBuilder.build(); notificationManager.notify(notifyID, notification); } catch (Exception e) { e.printStackTrace(); } }
/** Notify user about running server and connected clients */ public synchronized void notifyUser(String title, String message, boolean ongoing) { PendingIntent intent = PendingIntent.getActivity(AppContext, 0, new Intent(AppContext, main.class), 0); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) AppContext.getSystemService(ns); NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(AppContext); notificationbuilder.setContentTitle(title); notificationbuilder.setContentText(message); notificationbuilder.setTicker(message); notificationbuilder.setSmallIcon(R.drawable.ic_launcher); notificationbuilder.setContentIntent(intent); notificationbuilder.setOngoing(ongoing); Notification notification = notificationbuilder.getNotification(); mNotificationManager.notify(1, notification); }
private Notification generateNotification() { // 通知領域タップ時のPendingIntentを生成 Intent actionIntent = new Intent(getApplicationContext(), Ch0708.class); PendingIntent pi = PendingIntent.getActivity( getApplicationContext(), 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 独自レイアウトのRemoveViewを生成 RemoteViews mNotificationView = new RemoteViews(getPackageName(), R.layout.ch0708_statusbar); // Notificationの生成 NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); builder.setSmallIcon(R.drawable.ic_stat_media); // 独自レイアウトをNotificaitonに設定 builder.setContent(mNotificationView); // trueで常に通知領域に表示 builder.setOngoing(true); // 通知領域に初期表示時のメッセージを設定 builder.setTicker("Sample Titleを再生"); builder.setContentIntent(pi); // ステータスバーのレイアウトに設定されているイメージアイコンにアイコンを設定 mNotificationView.setImageViewResource(R.id.imageicon, R.drawable.ic_launcher); // ステータスバーのレイアウトに設定されているタイトル名にタイトルを設定 mNotificationView.setTextViewText(R.id.textTitle, "Sample Title"); // ステータスバーのレイアウトに設定されているアーティスト名にアーティストを設定 mNotificationView.setTextViewText(R.id.textArtist, "Sample Artist"); // [イメージアイコン]ボタンを押された際に呼ばれるIntentを設定 PendingIntent contentIntent = PendingIntent.getActivity( this, 0, new Intent(this, Ch0708.class), Intent.FLAG_ACTIVITY_NEW_TASK); mNotificationView.setOnClickPendingIntent(R.id.imageicon, contentIntent); // [再生]・[一時停止]ボタンを押された際に呼ばれるIntentを設定 mNotificationView.setOnClickPendingIntent(R.id.btnPlay, createPendingIntent("playpause")); // [次へ]ボタンを押された際に呼ばれるIntentを設定 mNotificationView.setOnClickPendingIntent(R.id.btnNext, createPendingIntent("next")); return builder.build(); }
private void showPostUpdateNotification() { // Remove the old one mNotificationManager.cancel(NOTIFICATION_ID); mBuilder = new NotificationCompat.Builder(getApplicationContext()); mBuilder.setTicker(getString(R.string.finishedTraktMovieSync)); mBuilder.setContentTitle(getString(R.string.finishedTraktMovieSync)); mBuilder.setSmallIcon(R.drawable.done); mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.done)); mBuilder.setOngoing(false); mBuilder.setAutoCancel(true); mBuilder.setOnlyAlertOnce(true); // Build notification Notification updateNotification = mBuilder.build(); // Show the notification mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIFICATION_ID + 1000, updateNotification); }
public void updateNotificationState(User user) { boolean muted = user.selfMuted; boolean deafened = user.selfDeafened; String status = null; if (muted && !deafened) { status = getString(R.string.status_notify_muted); } else if (deafened && muted) { status = getString(R.string.status_notify_muted_and_deafened); } mStatusNotificationBuilder.setTicker(status); mStatusNotificationBuilder.setContentInfo(status); mStatusNotificationBuilder.setSmallIcon(R.drawable.ic_stat_notify); mStatusNotification = mStatusNotificationBuilder.build(); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(STATUS_NOTIFICATION_ID, mStatusNotification); }
public int onStartCommand(Intent intent, int flags, int startId) { path = intent.getStringExtra("path"); if (path == null) { stopSelf(); return Service.START_NOT_STICKY; } FileLog.e("tmessages", "start video service"); if (builder == null) { builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext); builder.setSmallIcon(android.R.drawable.stat_sys_upload); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo)); builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo)); } currentProgress = 0; builder.setProgress(100, currentProgress, currentProgress == 0); startForeground(4, builder.build()); NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); return Service.START_NOT_STICKY; }
private void setupNotification() { // Setup up notification mBuilder = new NotificationCompat.Builder(getApplicationContext()); mBuilder.setSmallIcon(R.drawable.ic_action_tv); mBuilder.setTicker(getString(R.string.syncMovies)); mBuilder.setContentTitle(getString(R.string.syncMovies)); mBuilder.setContentText(getString(R.string.updatingMovieInfo)); mBuilder.setOngoing(true); mBuilder.setOnlyAlertOnce(true); mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_tv)); // Build notification Notification updateNotification = mBuilder.build(); // Show the notification mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIFICATION_ID, updateNotification); // Tell the system that this is an ongoing notification, so it shouldn't be killed startForeground(NOTIFICATION_ID, updateNotification); }
void showNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.ic_stat_notify); builder.setTicker(getResources().getString(R.string.plumbleConnected)); builder.setContentTitle(getResources().getString(R.string.app_name)); builder.setContentText(getResources().getString(R.string.connected)); builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setOngoing(true); // Add notification triggers Intent muteIntent = new Intent(this, MumbleService.class); muteIntent.putExtra(MUMBLE_NOTIFICATION_ACTION_KEY, MUMBLE_NOTIFICATION_ACTION_MUTE); Intent deafenIntent = new Intent(this, MumbleService.class); deafenIntent.putExtra(MUMBLE_NOTIFICATION_ACTION_KEY, MUMBLE_NOTIFICATION_ACTION_DEAFEN); builder.addAction( R.drawable.ic_action_microphone, getString(R.string.mute), PendingIntent.getService(this, 0, muteIntent, PendingIntent.FLAG_CANCEL_CURRENT)); builder.addAction( R.drawable.ic_action_headphones, getString(R.string.deafen), PendingIntent.getService(this, 1, deafenIntent, PendingIntent.FLAG_CANCEL_CURRENT)); Intent channelListIntent = new Intent(MumbleService.this, ChannelActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, channelListIntent, 0); builder.setContentIntent(pendingIntent); mStatusNotificationBuilder = builder; mStatusNotification = mStatusNotificationBuilder.build(); startForeground(STATUS_NOTIFICATION_ID, mStatusNotification); }
/** * Shows the notification with repost and discard options. Multiple Place-its listed as separate * notifications. */ public static void notify(final Context context, final int pID) { final Resources res = context.getResources(); PlaceIt placeIt = PlaceItList.find(pID); final String title = placeIt.getTitle(); // address for Categorical, Location cordinate for regular String address = placeIt.getDescription(); if (placeIt.getClass() == CategoricalPlaceIt.class) { address = ((CategoricalPlaceIt) placeIt).getAddress(); } else { address = "" + ((LocationPlaceIt) placeIt).getLocation().getLatitude() + ((LocationPlaceIt) placeIt).getLocation().getLongitude(); } final String fullTitle = res.getString(R.string.place_it_notification_title_template, title); final String fullAddress = res.getString(R.string.place_it_notification_text_template, address); final NotificationCompat.Builder notification = new NotificationCompat.Builder(context); // Set appropriate defaults for the notification light, sound, // and vibration. notification.setDefaults(Notification.DEFAULT_ALL); // required values notification.setSmallIcon(R.drawable.ic_launcher); notification.setContentTitle(fullTitle); notification.setContentText(fullAddress); // Set preview information for this notification. notification.setTicker(title); // On click action go to DescriptionActivity Intent descriptionIntent = new Intent(context, DescriptionActivity.class).putExtra(MainActivity.PLACEIT_ID, pID); notification.setContentIntent( PendingIntent.getActivity( context, pID, descriptionIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // Repost action Intent repostIntent = new Intent(context, PlaceItNotification.class) .putExtra(BUTTON_TAG, R.string.notification_repost) .putExtra(MainActivity.PLACEIT_ID, pID); notification.addAction( R.drawable.ic_stat_repost, res.getString(R.string.notification_repost), PendingIntent.getBroadcast(context, 0, repostIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // Discard action Intent discardIntent = new Intent(context, PlaceItNotification.class) .putExtra(BUTTON_TAG, R.string.notification_discard) .putExtra(MainActivity.PLACEIT_ID, pID); notification.addAction( R.drawable.ic_stat_discard, res.getString(R.string.notification_discard), PendingIntent.getBroadcast(context, 0, discardIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // Automatically dismiss the notification when it is touched. notification.setAutoCancel(true); notify(context, notification.build(), pID); }
private void onNotify( final SharedPreferences prefs, final Cursor upcomingEpisodes, int count, long latestAirtime) { final Context context = getApplicationContext(); CharSequence tickerText = ""; CharSequence contentTitle = ""; CharSequence contentText = ""; PendingIntent contentIntent = null; // notification sound final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context); // vibration final boolean isVibrating = NotificationSettings.isNotificationVibrating(context); if (count == 1) { // notify in detail about one episode upcomingEpisodes.moveToFirst(); final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE); final String airs = Utils.formatToTimeAndDay(upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[ 0]; final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); tickerText = getString(R.string.upcoming_show, showTitle); contentTitle = showTitle + " " + Utils.getEpisodeNumber( this, upcomingEpisodes.getInt(NotificationQuery.SEASON), upcomingEpisodes.getInt(NotificationQuery.NUMBER)); contentText = getString(R.string.upcoming_show_detailed, airs, network); Intent notificationIntent = new Intent(context, EpisodesActivity.class); notificationIntent.putExtra( EpisodesActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); contentIntent = PendingIntent.getActivity(context, REQUEST_CODE_SINGLE_EPISODE, notificationIntent, 0); } else if (count > 1) { // notify about multiple episodes tickerText = getString(R.string.upcoming_episodes); contentTitle = getString(R.string.upcoming_episodes_number, count); contentText = getString(R.string.upcoming_display); Intent notificationIntent = new Intent(context, UpcomingRecentActivity.class); notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); contentIntent = PendingIntent.getActivity(context, REQUEST_CODE_MULTIPLE_EPISODES, notificationIntent, 0); } final NotificationCompat.Builder nb = new NotificationCompat.Builder(context); if (AndroidUtils.isJellyBeanOrHigher()) { // JELLY BEAN and above if (count == 1) { // single episode upcomingEpisodes.moveToFirst(); final String imagePath = upcomingEpisodes.getString(NotificationQuery.POSTER); nb.setLargeIcon(ImageProvider.getInstance(context).getImage(imagePath, true)); final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE); final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW); final SpannableStringBuilder bigText = new SpannableStringBuilder(); bigText.append(episodeTitle); bigText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, bigText.length(), 0); bigText.append("\n"); bigText.append(episodeSummary); nb.setStyle( new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText)); // Action button to check in Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class); checkInActionIntent.putExtra( QuickCheckInActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID)); PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN, checkInActionIntent, 0); nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent); } else { // multiple episodes NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); // display at most the first five final int displayCount = Math.min(count, 5); for (int i = 0; i < displayCount; i++) { if (upcomingEpisodes.moveToPosition(i)) { // add show title, air time and network final SpannableStringBuilder lineText = new SpannableStringBuilder(); lineText.append(upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE)); lineText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, lineText.length(), 0); lineText.append(" "); String airs = Utils.formatToTimeAndDay( upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[0]; String network = upcomingEpisodes.getString(NotificationQuery.NETWORK); lineText.append(getString(R.string.upcoming_show_detailed, airs, network)); inboxStyle.addLine(lineText); } } // tell if we could not display all episodes if (count > 5) { inboxStyle.setSummaryText(getString(R.string.more, count - 5)); } nb.setStyle(inboxStyle); nb.setContentInfo(String.valueOf(count)); } } else { // ICS and below if (count == 1) { // single episode upcomingEpisodes.moveToFirst(); final String posterPath = upcomingEpisodes.getString(NotificationQuery.POSTER); nb.setLargeIcon(ImageProvider.getInstance(context).getImage(posterPath, true)); } } // If the string is empty, the user chose silent... if (ringtoneUri.length() != 0) { // ...otherwise set the specified ringtone nb.setSound(Uri.parse(ringtoneUri)); } if (isVibrating) { nb.setVibrate(VIBRATION_PATTERN); } nb.setDefaults(Notification.DEFAULT_LIGHTS); nb.setWhen(System.currentTimeMillis()); nb.setAutoCancel(true); nb.setTicker(tickerText); nb.setContentTitle(contentTitle); nb.setContentText(contentText); nb.setContentIntent(contentIntent); nb.setSmallIcon(R.drawable.ic_notification); nb.setPriority(NotificationCompat.PRIORITY_DEFAULT); Intent i = new Intent(this, NotificationService.class); i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime); PendingIntent deleteIntent = PendingIntent.getService(this, 1, i, 0); nb.setDeleteIntent(deleteIntent); // build the notification Notification notification = nb.build(); // use string resource id, always unique within app final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(R.string.upcoming_show, notification); }
private void showNotification( Context context, int notificationId, int smallIconId, String title, String contentText, String bigTitle, String bigContentText, String summaryText, String ticker, Intent intent) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSound(soundUri); if (smallIconId == 0) { builder.setSmallIcon(R.mipmap.ic_launcher); } else { builder.setSmallIcon(smallIconId); } builder.setWhen(System.currentTimeMillis()); // builder.setNumber(10); if (!StringUtils.isEmptyString(ticker)) { builder.setTicker(ticker); } if (StringUtils.isEmptyString(title)) { builder.setContentTitle(PackageUtils.getApplicationName(context)); } else { builder.setContentTitle(title); } builder.setContentText(contentText); builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); builder.setAutoCancel(true); // big title and text if (!StringUtils.isEmptyString(bigTitle) && !StringUtils.isEmptyString(bigContentText)) { NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(builder); if (!StringUtils.isEmptyString(summaryText)) { style.setSummaryText(summaryText); } style.setBigContentTitle(bigTitle); style.bigText(bigContentText); builder.setStyle(style); } if (intent != null) { intent.setFlags( intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity( context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); } notificationManager.notify(notificationId, builder.build()); }
/** * 发送通知栏提示 This can be override by subclass to provide customer implementation * * @param message */ protected void sendNotification(EMMessage message, boolean isForeground, boolean numIncrease) { String username = message.getFrom(); try { String notifyText = username + " "; switch (message.getType()) { case TXT: notifyText += msgs[0]; break; case IMAGE: notifyText += msgs[1]; break; case VOICE: notifyText += msgs[2]; break; case LOCATION: notifyText += msgs[3]; break; case VIDEO: notifyText += msgs[4]; break; case FILE: notifyText += msgs[5]; break; } PackageManager packageManager = appContext.getPackageManager(); String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo()); // notification titile String contentTitle = appname; if (notificationInfoProvider != null) { String customNotifyText = notificationInfoProvider.getDisplayedText(message); String customCotentTitle = notificationInfoProvider.getTitle(message); if (customNotifyText != null) { // 设置自定义的状态栏提示内容 notifyText = customNotifyText; } if (customCotentTitle != null) { // 设置自定义的通知栏标题 contentTitle = customCotentTitle; } } // create and send notificaiton NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext) .setSmallIcon(appContext.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(true); Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName); if (notificationInfoProvider != null) { // 设置自定义的notification点击跳转intent msgIntent = notificationInfoProvider.getLaunchIntent(message); } PendingIntent pendingIntent = PendingIntent.getActivity( appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (numIncrease) { // prepare latest event info section if (!isForeground) { notificationNum++; fromUsers.add(message.getFrom()); } } int fromUsersNum = fromUsers.size(); String summaryBody = msgs[6] .replaceFirst("%1", Integer.toString(fromUsersNum)) .replaceFirst("%2", Integer.toString(notificationNum)); if (notificationInfoProvider != null) { // lastest text String customSummaryBody = notificationInfoProvider.getLatestText(message, fromUsersNum, notificationNum); if (customSummaryBody != null) { summaryBody = customSummaryBody; } // small icon int smallIcon = notificationInfoProvider.getSmallIcon(message); if (smallIcon != 0) { mBuilder.setSmallIcon(smallIcon); } } mBuilder.setContentTitle(contentTitle); mBuilder.setTicker(notifyText); mBuilder.setContentText(summaryBody); mBuilder.setContentIntent(pendingIntent); // mBuilder.setNumber(notificationNum); Notification notification = mBuilder.build(); if (isForeground) { notificationManager.notify(foregroundNotifyID, notification); notificationManager.cancel(foregroundNotifyID); } else { notificationManager.notify(notifyID, notification); } } catch (Exception e) { e.printStackTrace(); } }
@Override public Builder setTicker(CharSequence tickerText, RemoteViews views) { super.setTicker(tickerText, views); return this; }
@Override public Builder setTicker(CharSequence tickerText) { super.setTicker(tickerText); return this; }
private void showNotification( int playState, int audioPath, String title, String artist, String album, Bitmap artwork) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle(title); if (artwork != null) { builder.setLargeIcon(artwork); } int icon = R.drawable.ic_launcher; if (audioPath == AUDIO_PATH_SPEAKER) { icon = R.drawable.ic_speaker; } else if (audioPath == AUDIO_PATH_A2DP) { icon = R.drawable.ic_a2dp; } else if (audioPath == AUDIO_PATH_WIRED) { icon = R.drawable.ic_wired; } builder.setSmallIcon(icon); builder.setTicker(title); builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setContentText(artist); builder.setSubText(album); PendingIntent pendingIntent = null; Intent intent = new Intent(this, PlaybackService.class); String keyTop; String action; if (playState == PLAY_STATE_PAUSED) { action = ACTION_PAUSE; keyTop = "Pause"; icon = android.R.drawable.ic_media_pause; intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_TRACK_DOWN); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_previous, "Prev", pendingIntent); } else { action = ACTION_PLAY; keyTop = "Play"; icon = android.R.drawable.ic_media_play; intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_STOP); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_delete, "Stop", pendingIntent); } intent = new Intent(this, PlaybackService.class); intent.setAction(action); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(icon, keyTop, pendingIntent); intent = new Intent(this, PlaybackService.class); intent.setAction(ACTION_TRACK_UP); pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_next, "Next", pendingIntent); intent = new Intent(this, SimpleMusicPlayer.class); pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); startForeground(R.id.notification_id, builder.build()); // startForeground(R.id.notification_id, new // NotificationCompat.InboxStyle(builder).addLine("test1").addLine("test2").build()); }