Esempio n. 1
0
  private void addListToDatabase(List list) {
    // Insert the list
    ContentValues values = new ContentValues();
    values.put(Lists.LIST_ID, list.listId);
    values.put(Lists.NAME, list.name);
    mContext.getContentResolver().insert(Lists.CONTENT_URI, values);

    if (list.items == null || list.items.isEmpty()) {
      return;
    }

    // Insert the lists items
    ArrayList<ContentValues> items = com.uwetrottmann.androidutils.Lists.newArrayList();
    for (ListItem item : list.items) {
      int type;
      if (ListItemTypesExport.SHOW.equals(item.type)) {
        type = ListItemTypes.SHOW;
      } else if (ListItemTypesExport.SEASON.equals(item.type)) {
        type = ListItemTypes.SEASON;
      } else if (ListItemTypesExport.EPISODE.equals(item.type)) {
        type = ListItemTypes.EPISODE;
      } else {
        // Unknown item type, skip
        continue;
      }
      ContentValues itemValues = new ContentValues();
      itemValues.put(ListItems.LIST_ITEM_ID, item.listItemId);
      itemValues.put(Lists.LIST_ID, list.listId);
      itemValues.put(ListItems.ITEM_REF_ID, item.tvdbId);
      itemValues.put(ListItems.TYPE, type);

      items.add(itemValues);
    }

    ContentValues[] itemsArray = new ContentValues[items.size()];
    mContext.getContentResolver().bulkInsert(ListItems.CONTENT_URI, items.toArray(itemsArray));
  }
  @TargetApi(android.os.Build.VERSION_CODES.KITKAT)
  @Override
  protected void onHandleIntent(Intent intent) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
      return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
      // cancel any pending alarm
      AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      Intent i = new Intent(this, OnAlarmReceiver.class);
      PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
      am.cancel(pi);

      resetLastEpisodeAirtime(prefs);

      return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    final long fakeNow = Utils.getFakeCurrentTime(prefs);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    if (isFavsOnly) {
      selection.append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    if (isNoSpecials) {
      selection.append(Episodes.SELECTION_NOSPECIALS);
    }
    final Cursor upcomingEpisodes =
        getContentResolver()
            .query(
                Episodes.CONTENT_URI_WITHSHOW,
                PROJECTION,
                selection.toString(),
                new String[] {String.valueOf(fakeNow - 12 * DateUtils.HOUR_IN_MILLIS)},
                SORTING);

    if (upcomingEpisodes != null) {
      int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
      if (DEBUG) {
        // a week, for debugging (use only one show to get single
        // episode notifications)
        notificationThreshold = 10080;
        // notify again for same episodes
        resetLastEpisodeAirtime(prefs);
      }
      final long latestTimeToInclude = fakeNow + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;
      final long nextTimePlanned = NotificationSettings.getNextToNotifyAbout(this);
      final long nextWakeUpPlanned =
          Utils.convertToFakeTime(nextTimePlanned, prefs, false)
              - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

      /*
       * Set to -1 as on first run nextTimePlanned will be 0. This assures
       * we still see notifications of upcoming episodes then.
       */
      int newEpisodesAvailable = -1;

      // Check if we did wake up earlier than planned
      if (System.currentTimeMillis() < nextWakeUpPlanned) {
        newEpisodesAvailable = 0;
        long latestTimeNotified = NotificationSettings.getLastNotified(this);

        // Check if there are any earlier episodes to notify about
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime < nextTimePlanned) {
            if (airtime > latestTimeNotified) {
              /**
               * This will not get new episodes which would have aired the same time as the last one
               * we notified about. Sad, but the best we can do right now.
               */
              newEpisodesAvailable = 1;
              break;
            }
          } else {
            break;
          }
        }
      }

      if (newEpisodesAvailable == 0) {
        // Go to sleep, wake up as planned
        wakeUpTime = nextWakeUpPlanned;
      } else {
        // Get episodes which are within the notification threshold
        // (user set) and not yet cleared
        int count = 0;
        final List<Integer> notifyPositions = Lists.newArrayList();
        final long latestTimeCleared = NotificationSettings.getLastCleared(this);

        upcomingEpisodes.moveToPosition(-1);
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime <= latestTimeToInclude) {
            count++;
            /*
             * Only add those after the last one the user cleared.
             * At most those of the last 24 hours (see query above).
             */
            if (airtime > latestTimeCleared) {
              notifyPositions.add(count);
            }
          } else {
            // Too far into the future, stop!
            break;
          }
        }

        // Notify if we found any episodes
        if (notifyPositions.size() > 0) {
          // store latest air time of all episodes we notified about
          upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
          long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (!AndroidUtils.isHoneycombOrHigher()) {
            /*
             * Everything below HC does not have delete intents, so
             * we just never notify about the same episode twice.
             */
            prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
          }
          prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

          onNotify(prefs, upcomingEpisodes, count, latestAirtime);
        }

        /*
         * Plan next episode to notify about, calc wake-up alarm as
         * early as user wants.
         */
        upcomingEpisodes.moveToPosition(-1);
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime > latestTimeToInclude) {
            // store next episode we plan to notify about
            prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, airtime).commit();

            // convert it to actual device time for setting the
            // alarm
            wakeUpTime =
                Utils.convertToFakeTime(airtime, prefs, false)
                    - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            break;
          }
        }
      }

      upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
      wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    if (AndroidUtils.isKitKatOrHigher()) {
      am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
      am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
  }