Beispiel #1
0
  public void updateNotification() {
    if (!Preferences.isNotificationEnabled() || !playServicesAvailable) return;

    String title = null;
    String subtitle = null;
    long time = 0;

    if ((this.lastPublishedLocation != null) && Preferences.isNotificationLocationEnabled()) {
      time = this.lastPublishedLocationTime.getTime();

      if ((this.lastPublishedLocation.getGeocoder() != null)
          && Preferences.isNotificationGeocoderEnabled()) {
        title = this.lastPublishedLocation.toString();
      } else {
        title = this.lastPublishedLocation.toLatLonString();
      }
    } else {
      title = this.context.getString(R.string.app_name);
    }

    subtitle =
        ServiceLocator.getStateAsString(this.context)
            + " | "
            + ServiceBroker.getStateAsString(this.context);

    notificationBuilder.setContentTitle(title);
    notificationBuilder
        .setSmallIcon(R.drawable.ic_notification)
        .setContentText(subtitle)
        .setPriority(android.support.v4.app.NotificationCompat.PRIORITY_MIN);
    if (time != 0) notificationBuilder.setWhen(this.lastPublishedLocationTime.getTime());

    this.notification = notificationBuilder.build();
    this.context.startForeground(Defaults.NOTIFCATION_ID, this.notification);
  }
  @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());
  }
  @Override
  public void onReceive(Context context, Intent bootIntent) {
    // Check if enabled
    if (!Utils.isXposedEnabled()) {
      // Create Xposed installer intent
      Intent xInstallerIntent =
          context.getPackageManager().getLaunchIntentForPackage("de.robv.android.xposed.installer");
      if (xInstallerIntent != null) xInstallerIntent.putExtra("opentab", 1);

      PendingIntent pi =
          (xInstallerIntent == null
              ? null
              : PendingIntent.getActivity(
                  context, 0, xInstallerIntent, PendingIntent.FLAG_UPDATE_CURRENT));

      // Build notification
      NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
      notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
      notificationBuilder.setContentTitle(context.getString(R.string.app_name));
      notificationBuilder.setContentText("PeerBlock For Android is not enabled in XPosed");
      notificationBuilder.setWhen(System.currentTimeMillis());
      notificationBuilder.setAutoCancel(true);
      if (pi != null) notificationBuilder.setContentIntent(pi);
      Notification notification = notificationBuilder.build();

      // Display notification
      NotificationManager notificationManager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      notificationManager.notify(0, notification);
    }
  }
  /**
   * @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());
  }
 /**
  * Generate a notification
  *
  * @param pendingIntent pending intent
  * @param title title
  * @param message message
  * @return the notification
  */
 private Notification buildNotification(
     PendingIntent pendingIntent, String title, String message) {
   NotificationCompat.Builder notif = new NotificationCompat.Builder(this);
   notif.setContentIntent(pendingIntent);
   notif.setSmallIcon(R.drawable.ri_notif_file_transfer_icon);
   notif.setWhen(System.currentTimeMillis());
   notif.setAutoCancel(true);
   notif.setOnlyAlertOnce(true);
   notif.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
   notif.setDefaults(Notification.DEFAULT_VIBRATE);
   notif.setContentTitle(title);
   notif.setContentText(message);
   return notif.build();
 }
    private void notify(String text, boolean ongoing) {
      NotificationCompat.Builder notificationBuilder =
          new NotificationCompat.Builder(ActivityMain.this);
      notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
      notificationBuilder.setContentTitle(getString(R.string.menu_import));
      notificationBuilder.setContentText(text);
      notificationBuilder.setWhen(System.currentTimeMillis());
      if (ongoing) notificationBuilder.setOngoing(true);
      else notificationBuilder.setAutoCancel(true);
      Notification notification = notificationBuilder.build();

      NotificationManager notificationManager =
          (NotificationManager) ActivityMain.this.getSystemService(Context.NOTIFICATION_SERVICE);
      notificationManager.notify(NOTIFY_ID, notification);
    }
  @Override
  public void onReceive(Context context, Intent intent) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.registration_notification);
    builder.setContentTitle(intent.getStringExtra(RegistrationService.NOTIFICATION_TITLE));
    builder.setContentText(intent.getStringExtra(RegistrationService.NOTIFICATION_TEXT));
    builder.setContentIntent(
        PendingIntent.getActivity(context, 0, new Intent(context, DialerActivity.class), 0));
    builder.setWhen(System.currentTimeMillis());
    builder.setDefaults(Notification.DEFAULT_VIBRATE);
    builder.setAutoCancel(true);

    Notification notification = builder.build();
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
        .notify(31337, notification);
  }
 /** 初始化通知栏 */
 private void initNotify() {
   mBuilder = new NotificationCompat.Builder(this);
   mBuilder
       .setWhen(System.currentTimeMillis()) // 通知产生的时间,会在通知信息里显示
       .setContentIntent(getDefalutIntent(0))
       // .setNumber(number)//显示数量
       .setPriority(Notification.PRIORITY_DEFAULT) // 设置该通知优先级
       // .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
       .setOngoing(
           false) // ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
       .setDefaults(
           Notification
               .DEFAULT_VIBRATE) // 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
       // Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 //
       // requires VIBRATE permission
       .setSmallIcon(R.drawable.icon);
 }
 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 addSessionInvitationNotification(Intent intent, ContactId contact) {
    /* Create pending intent */
    Intent invitation = new Intent(intent);
    String title;
    if (mMultimediaMessagingSession) {
      invitation.setClass(this, MessagingSessionView.class);
      title = getString(R.string.title_recv_messaging_session);
    } else {
      invitation.setClass(this, StreamingSessionView.class);
      title = getString(R.string.title_recv_streaming_session);
    }
    invitation.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    /*
     * If the PendingIntent has the same operation, action, data, categories, components, and
     * flags it will be replaced. Invitation should be notified individually so we use a random
     * generator to provide a unique request code and reuse it for the notification.
     */
    int uniqueId = Utils.getUniqueIdForPendingIntent();
    PendingIntent contentIntent =
        PendingIntent.getActivity(this, uniqueId, invitation, PendingIntent.FLAG_ONE_SHOT);

    String displayName = RcsContactUtil.getInstance(this).getDisplayName(contact);

    /* Create notification */
    NotificationCompat.Builder notif = new NotificationCompat.Builder(this);
    notif.setContentIntent(contentIntent);
    notif.setSmallIcon(R.drawable.ri_notif_mm_session_icon);
    notif.setWhen(System.currentTimeMillis());
    notif.setAutoCancel(true);
    notif.setOnlyAlertOnce(true);
    notif.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    notif.setDefaults(Notification.DEFAULT_VIBRATE);
    notif.setContentTitle(title);
    notif.setContentText(getString(R.string.label_from_args, displayName));

    /* Send notification */
    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(uniqueId, notif.build());
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Intent i = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
    String title = getString(R.string.notification_title);
    String content = getString(R.string.notification_state_locked);
    NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
    nb.setSmallIcon(R.drawable.ic_launcher);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);

    startForeground(AppLockService.NOTIFICATION_ID, nb.build());
    stopForeground(true);

    startForeground(MonitorService.NOTIFICATION_ID, nb.build());
    stopForeground(true);

    stopSelf();
    return START_NOT_STICKY;
  }
Beispiel #12
0
  @Override
  public void vaddStatNotif(final Context ctxt, final StatusMessage in) {
    StatusMessage m = validateStrings(in);

    if (m.getShow() != 1) {
      vcancel(ctxt, STAT_TAG, NotifUtil.STATNOTIFID);
      return;
    }

    if (NotifUtil.ssidStatus == NotifUtil.SSID_STATUS_UNMANAGED) {
      m.setStatus(
          new StringBuilder(ctxt.getString(R.string.unmanaged)).append(m.getStatus()).toString());
    }

    NotificationCompat.Builder statbuilder = new NotificationCompat.Builder(ctxt);
    Intent intent =
        new Intent(ctxt, WifiFixerActivity.class)
            .setAction(Intent.ACTION_MAIN)
            .setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    statbuilder.setContentIntent(PendingIntent.getActivity(ctxt, 0, intent, 0));
    statbuilder.setOnlyAlertOnce(true);
    statbuilder.setOngoing(true);
    statbuilder.setWhen(0);
    statbuilder.setPriority(NotificationCompat.PRIORITY_MIN);
    statbuilder.setSmallIcon(getIconfromSignal(m.getSignal(), ICON_SET_SMALL));
    statbuilder.setLargeIcon(
        BitmapFactory.decodeResource(
            ctxt.getResources(), getIconfromSignal(m.getSignal(), ICON_SET_LARGE)));
    statbuilder.setContentText(m.getStatus());
    statbuilder.setSubText(ctxt.getString(R.string.network_status));
    statbuilder.setContentTitle(m.getSSID());
    /*
     * Fire the notification
     */
    notify(ctxt, NotifUtil.STATNOTIFID, STAT_TAG, statbuilder.build());
  }
  public void notify(
      String notificationId,
      String apiKey,
      String title,
      String message,
      String uri,
      String imageUrl) {
    Log.d(LOGTAG, "notify()...");

    Log.d(LOGTAG, "notificationId=" + notificationId);
    Log.d(LOGTAG, "notificationApiKey=" + apiKey);
    Log.d(LOGTAG, "notificationTitle=" + title);
    Log.d(LOGTAG, "notificationMessage=" + message);
    Log.d(LOGTAG, "notificationUri=" + uri);

    if (isNotificationEnabled()) {
      // Show the toast
      if (isNotificationToastEnabled()) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
      }
      mBuilder
          .setWhen(System.currentTimeMillis()) // 通知产生的时间,会在通知信息里显示
          .setPriority(Notification.PRIORITY_DEFAULT) // 设置该通知优先级
          //				.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
          .setOngoing(
              false) // ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
          .setDefaults(
              Notification
                  .DEFAULT_VIBRATE) // 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
          // Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE
          // permission
          .setSmallIcon(getNotificationIcon());

      mBuilder
          .setAutoCancel(true) // 点击后让通知将消失
          .setContentTitle(title)
          .setContentText(message)
          .setTicker(message);
      // Notification
      if (isNotificationSoundEnabled()) {
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
      }
      if (isNotificationVibrateEnabled()) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
      }
      mBuilder.setOnlyAlertOnce(true);

      //            Intent intent;
      //            if (uri != null
      //                    && uri.length() > 0
      //                    && (uri.startsWith("http:") || uri.startsWith("https:")
      //                            || uri.startsWith("tel:") || uri.startsWith("geo:"))) {
      //                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
      //            } else {
      //                String callbackActivityPackageName = sharedPrefs.getString(
      //                        Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
      //                String callbackActivityClassName = sharedPrefs.getString(
      //                        Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
      //                intent = new Intent().setClassName(callbackActivityPackageName,
      //                        callbackActivityClassName);
      //                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      //                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      //            }

      Intent intent = new Intent(context, NotificationDetailsActivity.class);
      intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
      intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
      intent.putExtra(Constants.NOTIFICATION_TITLE, title);
      intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
      intent.putExtra(Constants.NOTIFICATION_URI, uri);
      intent.putExtra(Constants.NOTIFICATION_IMAGE_URL, imageUrl);

      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
      intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
      intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

      PendingIntent contentIntent =
          PendingIntent.getActivity(
              context, random.nextInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

      mBuilder.setContentIntent(contentIntent);
      notificationManager.notify(random.nextInt(), mBuilder.build());

    } else {
      Log.w(LOGTAG, "Notificaitons disabled.");
    }
  }
Beispiel #14
0
  private void showNotification(JSONObject message) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

    // These attributes are required
    final String id;
    try {
      builder.setContentTitle(message.getString(TITLE_ATTR));
      builder.setContentText(message.getString(TEXT_ATTR));
      id = message.getString(ID_ATTR);
    } catch (JSONException ex) {
      Log.i(LOGTAG, "Error parsing", ex);
      return;
    }

    Uri imageUri = Uri.parse(message.optString(SMALLICON_ATTR));
    builder.setSmallIcon(BitmapUtils.getResource(imageUri, R.drawable.ic_status_logo));

    JSONArray light = message.optJSONArray(LIGHT_ATTR);
    if (light != null && light.length() == 3) {
      try {
        builder.setLights(light.getInt(0), light.getInt(1), light.getInt(2));
      } catch (JSONException ex) {
        Log.i(LOGTAG, "Error parsing", ex);
      }
    }

    boolean ongoing = message.optBoolean(ONGOING_ATTR);
    builder.setOngoing(ongoing);

    if (message.has(WHEN_ATTR)) {
      long when = message.optLong(WHEN_ATTR);
      builder.setWhen(when);
    }

    if (message.has(PRIORITY_ATTR)) {
      int priority = message.optInt(PRIORITY_ATTR);
      builder.setPriority(priority);
    }

    if (message.has(LARGE_ICON_ATTR)) {
      Bitmap b = BitmapUtils.getBitmapFromDataURI(message.optString(LARGE_ICON_ATTR));
      builder.setLargeIcon(b);
    }

    if (message.has(PROGRESS_VALUE_ATTR)
        && message.has(PROGRESS_MAX_ATTR)
        && message.has(PROGRESS_INDETERMINATE_ATTR)) {
      try {
        final int progress = message.getInt(PROGRESS_VALUE_ATTR);
        final int progressMax = message.getInt(PROGRESS_MAX_ATTR);
        final boolean progressIndeterminate = message.getBoolean(PROGRESS_INDETERMINATE_ATTR);
        builder.setProgress(progressMax, progress, progressIndeterminate);
      } catch (JSONException ex) {
        Log.i(LOGTAG, "Error parsing", ex);
      }
    }

    JSONArray actions = message.optJSONArray(ACTIONS_ATTR);
    if (actions != null) {
      try {
        for (int i = 0; i < actions.length(); i++) {
          JSONObject action = actions.getJSONObject(i);
          final PendingIntent pending = buildButtonClickPendingIntent(message, action);
          final String actionTitle = action.getString(ACTION_TITLE_ATTR);
          final Uri actionImage = Uri.parse(action.optString(ACTION_ICON_ATTR));
          builder.addAction(
              BitmapUtils.getResource(actionImage, R.drawable.ic_status_logo),
              actionTitle,
              pending);
        }
      } catch (JSONException ex) {
        Log.i(LOGTAG, "Error parsing", ex);
      }
    }

    PendingIntent pi = buildNotificationPendingIntent(message, CLICK_EVENT);
    builder.setContentIntent(pi);
    PendingIntent deletePendingIntent = buildNotificationPendingIntent(message, CLEARED_EVENT);
    builder.setDeleteIntent(deletePendingIntent);

    GeckoAppShell.notificationClient.add(id.hashCode(), builder.build());

    boolean persistent = message.optBoolean(PERSISTENT_ATTR);
    // We add only not persistent notifications to the list since we want to purge only
    // them when geckoapp is destroyed.
    if (!persistent && !mClearableNotifications.containsKey(id)) {
      mClearableNotifications.put(id, message.toString());
    }
  }
 public void setTime(long time) {
   builder.setWhen(time);
 }
  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());
  }
  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());
  }
Beispiel #18
0
 @Override
 public Builder setWhen(long when) {
   super.setWhen(when);
   return this;
 }
  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);
  }