예제 #1
0
  public static void postIModNotification(Context context) {
    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    if (!MLPreferences.getPrefsApps(context)
        .getBoolean(Common.SHOW_IMOD_RESET_NOTIFICATION, false)) {
      nm.cancel(IMOD_NOTIFICATION_ID);
      return;
    }
    Intent notifyIntent = new Intent(context, ActionActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notifyIntent.putExtra(ActionsHelper.ACTION_EXTRA_KEY, R.id.radio_imod_reset);

    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.action_imod_reset))
            .setContentText("")
            .setSmallIcon(R.drawable.ic_apps_24dp)
            .setContentIntent(
                PendingIntent.getActivity(
                    context.getApplicationContext(),
                    0,
                    notifyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT))
            .setOngoing(true)
            .setAutoCancel(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      builder.setShowWhen(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      builder
          .setPriority(NotificationCompat.PRIORITY_MIN)
          .setCategory(NotificationCompat.CATEGORY_STATUS)
          .setColor(ContextCompat.getColor(context, R.color.accent));
    }
    nm.notify(IMOD_NOTIFICATION_ID, builder.build());
  }
예제 #2
0
 private void initBuilder(String title, String content) {
   builder = new NotificationCompat.Builder(baseActivity.getBaseContext());
   builder.setContentTitle(title);
   builder.setContentText(content);
   builder.setSmallIcon(R.drawable.ic_lets_go);
   builder.setPriority(NotificationCompat.PRIORITY_MAX);
   builder.setOngoing(true);
 }
예제 #3
0
  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());
  }
 @Override
 public NotificationCompat.Builder modifyNotificationBuilder(
     @NonNull NotificationCompat.Builder builder) {
   return builder
       .setPriority(NotificationCompat.PRIORITY_MAX)
       .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
       .setVibrate(new long[] {1, 1, 1})
       .setCategory(NotificationCompat.CATEGORY_MESSAGE)
       .setAutoCancel(true);
 }
예제 #5
0
  public static void postAppInstalledNotification(Context context, String packageName) {
    Intent neverShowAgain = new Intent(MAXLOCK_ACTION_NEVER_SHOW_AGAIN);
    neverShowAgain.setClass(context, NewAppInstalledBroadcastReceiver.class);
    Intent lockApp = new Intent(MAXLOCK_ACTION_LOCK_APP);
    lockApp.setClass(context, NewAppInstalledBroadcastReceiver.class);
    lockApp.putExtra(EXTRA_PACKAGE_NAME, packageName);

    String appName;
    try {
      appName =
          context
              .getPackageManager()
              .getApplicationInfo(packageName, 0)
              .loadLabel(context.getPackageManager())
              .toString();
    } catch (PackageManager.NameNotFoundException e) {
      appName = packageName;
    }

    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.notification_lock_new_app_title))
            .setContentText(appName)
            .setSmallIcon(R.drawable.ic_lock_48dp)
            .setAutoCancel(true)
            .addAction(
                new NotificationCompat.Action(
                    0,
                    context.getString(R.string.notification_lock_new_app_action_never_again),
                    PendingIntent.getBroadcast(
                        context, 0, neverShowAgain, PendingIntent.FLAG_UPDATE_CURRENT)))
            .addAction(
                new NotificationCompat.Action(
                    0,
                    context.getString(R.string.notification_lock_new_app_action_lock),
                    PendingIntent.getBroadcast(
                        context, 0, lockApp, PendingIntent.FLAG_UPDATE_CURRENT)));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      builder
          .setPriority(NotificationCompat.PRIORITY_HIGH)
          .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
          .setColor(ContextCompat.getColor(context, R.color.accent));
      try {
        builder.setVibrate(new long[0]);
      } catch (SecurityException e) {
        e.printStackTrace();
      }
    }
    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(APP_INSTALLED_NOTIFICATION_ID, builder.build());
  }
 private void setNotificationPriority(Bundle extras, NotificationCompat.Builder mBuilder) {
   String priorityStr = extras.getString(PRIORITY);
   if (priorityStr != null) {
     try {
       Integer priority = Integer.parseInt(priorityStr);
       if (priority >= NotificationCompat.PRIORITY_MIN
           && priority <= NotificationCompat.PRIORITY_MAX) {
         mBuilder.setPriority(priority);
       } else {
         Log.e(LOG_TAG, "Priority parameter must be between -2 and 2");
       }
     } catch (NumberFormatException e) {
       e.printStackTrace();
     }
   }
 }
예제 #7
0
  @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());
  }
  /**
   * Shows or hides the persistent notification based on running state and {@link
   * #PREF_NOTIFICATION_TYPE}.
   */
  private void updateNotification() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    String type = sp.getString(PREF_NOTIFICATION_TYPE, "low_priority");
    boolean foreground = sp.getBoolean(PREF_FOREGROUND_SERVICE, false);
    if ("none".equals(type) && foreground) {
      // foreground priority requires any notification
      // so this ensures that we either have a "default" or "low_priority" notification,
      // but not "none".
      type = "low_priority";
    }
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if ((mCurrentState == State.ACTIVE || mCurrentState == State.STARTING)
        && !type.equals("none")) {
      Context appContext = getApplicationContext();
      NotificationCompat.Builder builder =
          new NotificationCompat.Builder(appContext)
              .setContentTitle(getString(R.string.syncthing_active))
              .setSmallIcon(R.drawable.ic_stat_notify)
              .setOngoing(true)
              .setContentIntent(
                  PendingIntent.getActivity(
                      appContext, 0, new Intent(appContext, MainActivity.class), 0));
      if (type.equals("low_priority")) builder.setPriority(NotificationCompat.PRIORITY_MIN);

      if (foreground) {
        builder.setContentText(getString(R.string.syncthing_active_foreground));
        startForeground(NOTIFICATION_ACTIVE, builder.build());
      } else {
        stopForeground(false); // ensure no longer running with foreground priority
        nm.notify(NOTIFICATION_ACTIVE, builder.build());
      }
    } else {
      // ensure no longer running with foreground priority
      stopForeground(false);
      nm.cancel(NOTIFICATION_ACTIVE);
    }
  }
예제 #9
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);
  }
예제 #10
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());
  }
예제 #11
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());
    }
  }
예제 #12
0
 @Override
 public Builder setPriority(int pri) {
   super.setPriority(pri);
   return this;
 }
예제 #13
0
  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 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());
  }
예제 #15
0
  private boolean updateNotification(final Context context) {
    Log.d(TAG, "updateNotification()");
    lastUpdate = System.currentTimeMillis();
    NotificationManager nm =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    ArrayList<Timer> timers = new ArrayList<Timer>();
    mNow = System.currentTimeMillis();
    mNextTarget = 0;
    boolean alert = false;
    Log.d(TAG, "mNow: " + mNow);

    for (int j = 0; j < Timer.TIMER_IDS.length; j++) {
      Timer t = new Timer(context, j);
      timers.add(t);
      long tt = t.getTarget();
      Log.d(TAG, "target(" + j + "): " + tt);

      if (tt > 0) {
        if (mNextTarget == 0 || tt < mNextTarget) {
          mNextTarget = tt;
        }
        if (tt < mNow) {
          alert = true;
          t.reset(context);
        }
      }
    }
    Log.d(TAG, "mNextTarget: " + mNextTarget);

    NotificationCompat.Builder b = new NotificationCompat.Builder(context);
    b.setPriority(1000);
    Intent i = new Intent(context, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT));

    b.setContentTitle(context.getString(R.string.app_name));
    b.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
    b.setSmallIcon(R.drawable.ic_stat_timer);
    b.setAutoCancel(false);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // GB-
      b.setContentText(
          context.getString(
              R.string.notification_text,
              timers.get(0).getFormatted(),
              timers.get(1).getFormatted(),
              timers.get(2).getFormatted()));
    } else { // HC+
      RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.notification);
      for (int j = 0; j < Timer.TIMER_IDS.length; j++) {
        v.setTextViewText(Timer.TIMER_IDS[j], timers.get(j).getFormatted().toString());
        Intent ij = new Intent(Timer.TIMER_KEYS[j], null, context, UpdateReceiver.class);
        v.setOnClickPendingIntent(
            Timer.TIMER_IDS[j],
            PendingIntent.getBroadcast(context, 0, ij, PendingIntent.FLAG_UPDATE_CURRENT));
      }
      v.setOnClickPendingIntent(
          R.id.settings,
          PendingIntent.getActivity(
              context,
              0,
              new Intent(context, SettingsActivity.class),
              PendingIntent.FLAG_UPDATE_CURRENT));
      b.setContent(v);
    }

    if (mNextTarget <= 0 && !alert) {
      // we don't need any notification
      b.setOngoing(false);
      nm.notify(0, b.build());
      return false;
    } else if (alert) {
      // show notification without running Timer
      b.setOngoing(mNextTarget > 0);
      SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
      if (p.getBoolean("vibrate", true)) {
        b.setVibrate(VIBRATE);
      }
      String n = p.getString("notification", null);
      if (n == null) { // default
        b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
      } else if (n.length() > 1) {
        try {
          b.setSound(Uri.parse(n));
        } catch (Exception e) {
          Log.e(TAG, "invalid notification uri", e);
          b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
      } // else: silent
      nm.notify(0, b.build());
      return true;
    } else {
      // show notification with running Timer
      b.setOngoing(true);
      nm.notify(0, b.build());
      return true;
    }
  }
예제 #16
0
  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);
  }