public static void showNotActivatedNotification(String packageName, String appName) {
    Intent intent = new Intent(sContext, WelcomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("fragment", 1);

    PendingIntent pModulesTab =
        PendingIntent.getActivity(
            sContext, PENDING_INTENT_OPEN_MODULES, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    String title = sContext.getString(R.string.module_is_not_activated_yet);
    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(sContext)
            .setContentTitle(title)
            .setContentText(appName)
            .setTicker(title)
            .setContentIntent(pModulesTab)
            .setVibrate(new long[] {0})
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setColor(sContext.getResources().getColor(R.color.colorPrimary));

    if (Build.VERSION.SDK_INT >= 21) builder.setPriority(2);

    Intent iActivateAndReboot = new Intent(sContext, RebootReceiver.class);
    iActivateAndReboot.putExtra(RebootReceiver.EXTRA_ACTIVATE_MODULE, packageName);
    PendingIntent pActivateAndReboot =
        PendingIntent.getBroadcast(
            sContext,
            PENDING_INTENT_ACTIVATE_MODULE_AND_REBOOT,
            iActivateAndReboot,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent iActivate = new Intent(sContext, RebootReceiver.class);
    iActivate.putExtra(RebootReceiver.EXTRA_ACTIVATE_MODULE, packageName);
    iActivate.putExtra(RebootReceiver.EXTRA_ACTIVATE_MODULE_AND_RETURN, true);
    PendingIntent pActivate =
        PendingIntent.getBroadcast(
            sContext, PENDING_INTENT_ACTIVATE_MODULE, iActivate, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.BigTextStyle notiStyle = new NotificationCompat.BigTextStyle();
    notiStyle.setBigContentTitle(title);
    notiStyle.bigText(sContext.getString(R.string.module_is_not_activated_yet_detailed, appName));
    builder.setStyle(notiStyle);

    // Only show the quick activation button if any module has been
    // enabled before,
    // to ensure that the user know the way to disable the module later.
    if (!ModuleUtil.getInstance().getEnabledModules().isEmpty()) {
      builder.addAction(
          R.drawable.ic_menu_refresh,
          sContext.getString(R.string.activate_and_reboot),
          pActivateAndReboot);
      builder.addAction(R.drawable.ic_save, sContext.getString(R.string.activate_only), pActivate);
    }

    sNotificationManager.notify(
        packageName, NOTIFICATION_MODULE_NOT_ACTIVATED_YET, builder.build());
  }
Beispiel #2
0
  private void createNotification() {
    Log.v(this.toString(), "createNotification");
    //
    notificationBuilder = new NotificationCompat.Builder(this.context);

    Intent resultIntent = new Intent(this.context, ActivityLauncher.class);
    resultIntent.setAction("android.intent.action.MAIN");
    resultIntent.addCategory("android.intent.category.LAUNCHER");

    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent resultPendingIntent =
        PendingIntent.getActivity(this.context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationBuilder.setContentIntent(resultPendingIntent);

    this.notificationIntent =
        ServiceProxy.getPendingIntentForService(
            this.context,
            ServiceProxy.SERVICE_LOCATOR,
            Defaults.INTENT_ACTION_PUBLISH_LASTKNOWN,
            null);
    notificationBuilder.addAction(
        R.drawable.ic_action_upload,
        this.context.getString(R.string.publish),
        this.notificationIntent);
    updateNotification();
  }
  private void createActions(
      Bundle extras, NotificationCompat.Builder mBuilder, Resources resources, String packageName) {
    Log.d(LOG_TAG, "create actions");
    String actions = getString(extras, ACTIONS);
    if (actions != null) {
      try {
        JSONArray actionsArray = new JSONArray(actions);
        for (int i = 0; i < actionsArray.length(); i++) {
          Log.d(LOG_TAG, "adding action");
          JSONObject action = actionsArray.getJSONObject(i);
          Log.d(LOG_TAG, "adding callback = " + action.getString(CALLBACK));
          Intent intent = new Intent(this, PushHandlerActivity.class);
          intent.putExtra(CALLBACK, action.getString(CALLBACK));
          intent.putExtra(PUSH_BUNDLE, extras);
          PendingIntent pIntent =
              PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);

          mBuilder.addAction(
              resources.getIdentifier(action.getString(ICON), DRAWABLE, packageName),
              action.getString(TITLE),
              pIntent);
        }
      } catch (JSONException e) {
        // nope
      }
    }
  }
  private Notification getNotification() {
    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.launcher_icon)
            .setContentTitle("SleepMinder is active")
            .setContentText("Sleep well :)");

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, MainActivity.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(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.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);

    mBuilder.setProgress(0, 0, true);
    mBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);

    mBuilder.setOngoing(true);

    PendingIntent stopTrackingIntent =
        PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.addAction(R.drawable.ic_action_stop, "Stop tracking", stopTrackingIntent);

    return mBuilder.build();
  }
Beispiel #5
0
 @Override
 public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
   NotificationCompat.Action action = new NotificationCompat.Action(icon, title, intent);
   actions.add(action);
   super.addAction(icon, title, intent);
   return this;
 }
  private void showNotification() {

    mNotifMGR = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);

    // notification for the task bar
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.ic_music);
    builder.setContentTitle(mArtist[mSong]);
    builder.setContentText(mTitle[mSong]);
    builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong]));
    builder.setAutoCancel(false);
    builder.setOngoing(true);

    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
    style.setBigContentTitle(mArtist[mSong]);
    style.setSummaryText(mTitle[mSong]);
    style.bigLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_music));
    style.bigPicture(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong]));

    builder.setStyle(style);

    Intent skipIntent = new Intent(PREV_TRACK);
    PendingIntent pIntent =
        PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.addAction(android.R.drawable.ic_media_rew, "Last Track", pIntent);

    skipIntent = new Intent(NEXT_TRACK);
    pIntent = PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.addAction(android.R.drawable.ic_media_ff, "Next Track", pIntent);

    Intent clickIntent = new Intent(this, MainActivity.class);
    clickIntent.putExtra(MainFragment.EXTRA_TITLE_UPDATE, mTitle[mSong]);
    clickIntent.putExtra(MainFragment.EXTRA_COVER_UPDATE, mArtwork[mSong]);
    clickIntent.putExtra(MainFragment.EXTRA_ARTIST_UPDATE, mArtist[mSong]);
    clickIntent.putExtra(MainFragment.EXTRA_SONG_DURATION, mPlayer.getDuration());

    PendingIntent pendClickIntent =
        PendingIntent.getActivity(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendClickIntent);

    Notification notification = builder.build();
    startForeground(NOTIF_ID, notification);
  }
  @SuppressWarnings("deprecation")
  public static void showModulesUpdatedNotification() {
    Intent intent = new Intent(sContext, WelcomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("fragment", 0);

    PendingIntent pInstallTab =
        PendingIntent.getActivity(
            sContext, PENDING_INTENT_OPEN_INSTALL, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    String title = sContext.getString(R.string.xposed_module_updated_notification_title);
    String message = sContext.getString(R.string.xposed_module_updated_notification);
    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(sContext)
            .setContentTitle(title)
            .setContentText(message)
            .setTicker(title)
            .setContentIntent(pInstallTab)
            .setVibrate(new long[] {0})
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_notification)
            .setColor(sContext.getResources().getColor(R.color.colorPrimary));

    if (Build.VERSION.SDK_INT >= 21) builder.setPriority(2);

    Intent iSoftReboot = new Intent(sContext, RebootReceiver.class);
    iSoftReboot.putExtra(RebootReceiver.EXTRA_SOFT_REBOOT, true);
    PendingIntent pSoftReboot =
        PendingIntent.getBroadcast(
            sContext, PENDING_INTENT_SOFT_REBOOT, iSoftReboot, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent iReboot = new Intent(sContext, RebootReceiver.class);
    PendingIntent pReboot =
        PendingIntent.getBroadcast(
            sContext, PENDING_INTENT_REBOOT, iReboot, PendingIntent.FLAG_UPDATE_CURRENT);

    builder.addAction(0, sContext.getString(R.string.reboot), pReboot);
    builder.addAction(0, sContext.getString(R.string.soft_reboot), pSoftReboot);

    sNotificationManager.notify(null, NOTIFICATION_MODULES_UPDATED, builder.build());
  }
 public void createNewNotification(String title, String content) {
   initBuilder(title, content);
   initBigTextStyle(title, content);
   builder.setStyle(bigTextStyle);
   initNotificationIntent();
   initExitNavigationIntent();
   initStackBuilder(notificationIntent);
   builder.addAction(R.drawable.ic_dismiss, "Exit Navigation", pendingExitNavigationIntent);
   builder.setContentIntent(
       pendingNotificationIntent.getActivity(
           baseActivity.getApplicationContext(), 0, notificationIntent, 0));
   mNotificationManager.notify("route", 0, builder.build());
 }
  public Notification createNotification() {
    mNotifyBuild =
        new NotificationCompat.Builder(mController.getApplicationContext())
            .setContentTitle(mController.getString(R.string.balatafm))
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(getPendingIntent());

    mNotifyBuild.setContentText(getNotificationString());

    if (mPlayerState.isBuffering()) {
      mNotifyBuild.setProgress(0, 0, true);
    } else {
      if (mPlayerState.isPlaying()) {
        mNotifyBuild.addAction(R.drawable.player_stop, "Stop", getBroadcastIntent("stop"));
        mNotifyBuild.setOngoing(true);
      } else {
        mNotifyBuild.addAction(R.drawable.player_play, "Play", getBroadcastIntent("play"));
      }
    }

    mNotificationVisible = true;
    return mNotifyBuild.build();
  }
Beispiel #10
0
  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);
  }
  private Notification getNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder
        .setSmallIcon(R.drawable.ic_stat_notify_24dp)
        .setColor(getResources().getColor(R.color.primary))
        .setContentTitle(
            getResources()
                .getQuantityString(
                    R.plurals.passp_cache_notif_n_keys,
                    mPassphraseCache.size(),
                    mPassphraseCache.size()))
        .setContentText(getString(R.string.passp_cache_notif_touch_to_clear));

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.setBigContentTitle(getString(R.string.passp_cache_notif_keys));

    // Moves events into the big view
    for (int i = 0; i < mPassphraseCache.size(); i++) {
      inboxStyle.addLine(mPassphraseCache.valueAt(i).mPrimaryUserId);
    }

    // Moves the big view style object into the notification object.
    builder.setStyle(inboxStyle);

    Intent intent = new Intent(getApplicationContext(), PassphraseCacheService.class);
    intent.setAction(ACTION_PASSPHRASE_CACHE_CLEAR);
    PendingIntent clearCachePi =
        PendingIntent.getService(
            getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Add cache clear PI to normal touch
    builder.setContentIntent(clearCachePi);

    // Add clear PI action below text
    builder.addAction(
        R.drawable.ic_close_white_24dp, getString(R.string.passp_cache_notif_clear), clearCachePi);

    return builder.build();
  }
Beispiel #12
0
  // NOTIFICATION!
  public void startNotification() {
    String titlee = "Hey Good Looking";
    String contente = "Whats cooking?";

    File f = getBaseContext().getFileStreamPath("Done.txt");
    if (!f.exists()) return;

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
            .setContentTitle(titlee)
            .setContentText(contente)
            .setAutoCancel(true)
            .setVibrate(new long[100])
            .setPriority(Notification.PRIORITY_MAX);

    if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);

    Intent resultIntent = new Intent(this, OpenCamera.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.addAction(0, "Take a Selfie!", resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(0, mBuilder.build());

    try {
      FileOutputStream fos = openFileOutput("Done.txt", Context.MODE_APPEND);
      fos.write(("yio").getBytes());
      fos.close();
    } catch (Exception e) {
    }
  }
Beispiel #13
0
  /**
   * Called if the upload fails while If the content field is not empty, there will be an option to
   * retry
   *
   * @param title The title used for the upload
   * @param description The description used for the upload
   * @param content The url or file path of the uploaded photo
   */
  private void onUploadFailed(
      @Nullable String title,
      @Nullable String description,
      @Nullable String content,
      boolean wasFile) {
    mBuilder
        .setContentTitle(getString(R.string.error))
        .setContentText(getString(R.string.upload_error))
        .setProgress(0, 0, false)
        .setContentInfo(null);

    if (!TextUtils.isEmpty(content)) {
      Intent intent =
          NotificationReceiver.createRetryUploadIntent(
              getApplicationContext(), content, title, description, mNotificationId, wasFile);
      PendingIntent pIntent =
          PendingIntent.getBroadcast(
              getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
      mBuilder.addAction(R.drawable.ic_action_upload, getString(R.string.retry), pIntent);
    }

    mManager.notify(mNotificationId, mBuilder.build());
    stopSelf();
  }
  /**
   * 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);
  }
Beispiel #15
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());
    }
  }
  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 #17
0
  private void showNotification() {
    String[] projection =
        new String[] {
          PodcastProvider.COLUMN_ID,
          PodcastProvider.COLUMN_TITLE,
          PodcastProvider.COLUMN_SUBSCRIPTION_ID,
          PodcastProvider.COLUMN_SUBSCRIPTION_TITLE,
          PodcastProvider.COLUMN_SUBSCRIPTION_THUMBNAIL,
        };
    Cursor c =
        getContentResolver()
            .query(PodcastProvider.ACTIVE_PODCAST_URI, projection, null, null, null);
    if (c == null) return;
    if (c.isAfterLast()) {
      c.close();
      return;
    }
    PodcastCursor podcast = new PodcastCursor(c);

    // both paths use the pendingintent
    Intent showIntent = new Intent(this, MainActivity.class);
    PendingIntent showPendingIntent = PendingIntent.getActivity(this, 0, showIntent, 0);

    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setWhen(0)
            .setContentTitle(podcast.getTitle())
            .setContentText(podcast.getSubscriptionTitle())
            .setContentIntent(showPendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    // set up pause intent
    Intent pauseIntent = new Intent(this, PlayerService.class);
    // use data to make intent unique
    pauseIntent.setData(Uri.parse("podax://playercommand/playpause"));
    pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND, Constants.PLAYER_COMMAND_PLAYPAUSE);
    pauseIntent.putExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, Constants.PAUSE_MEDIABUTTON);
    PendingIntent pausePendingIntent = PendingIntent.getService(this, 0, pauseIntent, 0);

    // set up forward intent
    Intent forwardIntent = new Intent(this, ActivePodcastReceiver.class);
    forwardIntent.setData(Constants.ACTIVE_PODCAST_DATA_FORWARD);
    PendingIntent forwardPendingIntent = PendingIntent.getService(this, 0, forwardIntent, 0);

    Bitmap subscriptionBitmap =
        Helper.getCachedImage(this, podcast.getSubscriptionThumbnailUrl(), 128, 128);
    if (subscriptionBitmap != null) builder.setLargeIcon(subscriptionBitmap);

    if (PlayerStatus.getPlayerState(this) == PlayerStates.PLAYING)
      builder.addAction(
          R.drawable.ic_media_pause_normal, getString(R.string.pause), pausePendingIntent);
    else
      builder.addAction(
          R.drawable.ic_media_play_normal, getString(R.string.play), pausePendingIntent);
    builder.addAction(
        R.drawable.ic_media_ff_normal, getString(R.string.fast_forward), forwardPendingIntent);

    Notification notification = builder.build();
    startForeground(Constants.NOTIFICATION_PLAYING, notification);

    c.close();
  }
  private void createActions(
      Bundle extras,
      NotificationCompat.Builder mBuilder,
      Resources resources,
      String packageName,
      int notId) {
    Log.d(LOG_TAG, "create actions: with in-line");
    String actions = extras.getString(ACTIONS);
    String jsondata = extras.getString("json");
    if (actions != null) {
      try {
        JSONObject jsonobj = new JSONObject(jsondata);
        JSONArray actionsArray = new JSONArray(actions);
        ArrayList<NotificationCompat.Action> wActions = new ArrayList<NotificationCompat.Action>();
        for (int i = 0; i < actionsArray.length(); i++) {
          int min = 1;
          int max = 2000000000;
          Random random = new Random();
          int uniquePendingIntentRequestCode = random.nextInt((max - min) + 1) + min;
          Log.d(LOG_TAG, "adding action");
          JSONObject action = actionsArray.getJSONObject(i);
          Log.d(LOG_TAG, "adding callback = " + action.getString(CALLBACK));
          boolean foreground = action.optBoolean(FOREGROUND, true);
          boolean inline = action.optBoolean("inline", false);
          Intent intent = null;
          Log.d(LOG_TAG, "createActions=>type==isForeground: " + String.valueOf(foreground));
          PendingIntent pIntent = null;
          if (inline) {
            Log.d(
                LOG_TAG,
                "Version: "
                    + android.os.Build.VERSION.SDK_INT
                    + " = "
                    + android.os.Build.VERSION_CODES.M);
            if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.M) {
              Log.d(LOG_TAG, "push activity");
              intent = new Intent(this, PushHandlerActivity.class);
            } else {
              Log.d(LOG_TAG, "push receiver");
              intent = new Intent(this, BackgroundActionButtonHandler.class);
            }

            updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);

            if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.M) {
              Log.d(LOG_TAG, "push activity for notId " + notId);
              pIntent =
                  PendingIntent.getActivity(
                      this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_ONE_SHOT);
            } else {
              Log.d(LOG_TAG, "push receiver for notId " + notId);
              pIntent =
                  PendingIntent.getBroadcast(
                      this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_ONE_SHOT);
            }
          } else if (foreground) {
            intent = new Intent(this, PushHandlerActivity.class);
            updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);
            pIntent =
                PendingIntent.getActivity(
                    this,
                    uniquePendingIntentRequestCode,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
          } else {
            Log.d(
                LOG_TAG,
                "createActions=>Handling Action for background " + jsonobj.getString("type"));
            if (jsonobj.getString("type").equals("nowRequests")) {
              Log.d(LOG_TAG, "createActions=>type==nowRequests ");
              intent = new Intent(this, BackgroundRestActionButtonHandler.class);
            } else {
              intent = new Intent(this, BackgroundActionButtonHandler.class);
            }
            updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);
            pIntent =
                PendingIntent.getBroadcast(
                    this,
                    uniquePendingIntentRequestCode,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
          }

          NotificationCompat.Action.Builder actionBuilder =
              new NotificationCompat.Action.Builder(
                  resources.getIdentifier(action.optString(ICON, ""), DRAWABLE, packageName),
                  action.getString(TITLE),
                  pIntent);

          RemoteInput remoteInput = null;
          if (inline) {
            Log.d(LOG_TAG, "create remote input");
            String replyLabel = "Enter your reply here";
            remoteInput = new RemoteInput.Builder(INLINE_REPLY).setLabel(replyLabel).build();
            actionBuilder.addRemoteInput(remoteInput);
          }

          NotificationCompat.Action wAction = actionBuilder.build();
          wActions.add(actionBuilder.build());

          if (inline) {
            mBuilder.addAction(wAction);
          } else {
            mBuilder.addAction(
                resources.getIdentifier(action.optString(ICON, ""), DRAWABLE, packageName),
                action.getString(TITLE),
                pIntent);
          }
          wAction = null;
          pIntent = null;
        }
        mBuilder.extend(new WearableExtender().addActions(wActions));
        wActions.clear();
      } catch (JSONException e) {
        // nope
      }
    }
  }
  public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
      Conversation[] conversations =
          Database.getInstance(applicationContext).getConversations(preferences.getDid());
      for (Conversation conversation : conversations) {
        if (!conversation.isUnread()
            || !contacts.contains(conversation.getContact())
            || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                    .getContact()
                    .equals(conversation.getContact()))) {
          continue;
        }

        String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
        if (smsContact == null) {
          smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
        }

        String allSmses = "";
        String mostRecentSms = "";
        boolean initial = true;
        for (Message message : conversation.getMessages()) {
          if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
            if (initial) {
              allSmses = message.getText();
              mostRecentSms = message.getText();
              initial = false;
            } else {
              allSmses = message.getText() + "\n" + allSmses;
            }
          } else {
            break;
          }
        }

        NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(applicationContext);

        notificationBuilder.setContentTitle(smsContact);
        notificationBuilder.setContentText(mostRecentSms);
        notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
        notificationBuilder.setSound(
            Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
        notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
        if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
          notificationBuilder.setVibrate(new long[] {0, 250, 250, 250});
        } else {
          notificationBuilder.setVibrate(new long[] {0});
        }
        notificationBuilder.setColor(0xFFAA0000);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

        Bitmap largeIconBitmap;
        try {
          largeIconBitmap =
              MediaStore.Images.Media.getBitmap(
                  applicationContext.getContentResolver(),
                  Uri.parse(
                      Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
          largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
          largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
          notificationBuilder.setLargeIcon(largeIconBitmap);
        } catch (Exception ignored) {

        }

        Intent intent = new Intent(applicationContext, ConversationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
        stackBuilder.addParentStack(ConversationActivity.class);
        stackBuilder.addNextIntent(intent);
        notificationBuilder.setContentIntent(
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

        Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        } else {
          //noinspection deprecation
          replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        }
        replyIntent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        PendingIntent replyPendingIntent =
            PendingIntent.getActivity(
                applicationContext, 0, replyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Action.Builder replyAction =
            new NotificationCompat.Action.Builder(
                R.drawable.ic_reply_white_24dp,
                applicationContext.getString(R.string.notifications_button_reply),
                replyPendingIntent);
        notificationBuilder.addAction(replyAction.build());

        Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
        markAsReadIntent.putExtra(
            applicationContext.getString(R.string.conversation_extra_contact),
            conversation.getContact());
        PendingIntent markAsReadPendingIntent =
            PendingIntent.getBroadcast(
                applicationContext, 0, markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Action.Builder markAsReadAction =
            new NotificationCompat.Action.Builder(
                R.drawable.ic_drafts_white_24dp,
                applicationContext.getString(R.string.notifications_button_mark_read),
                markAsReadPendingIntent);
        notificationBuilder.addAction(markAsReadAction.build());

        int id;
        if (notificationIds.get(conversation.getContact()) != null) {
          id = notificationIds.get(conversation.getContact());
        } else {
          id = notificationIdCount++;
          notificationIds.put(conversation.getContact(), id);
        }
        NotificationManager notificationManager =
            (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, notificationBuilder.build());
      }
    }
  }
  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);
  }
Beispiel #21
0
 @Override
 public Builder addAction(NotificationCompat.Action action) {
   actions.add(action);
   super.addAction(action);
   return this;
 }