@Override
  public void onSortSelected(boolean always, int flags, int sort) {
    boolean manualSettingChanged =
        SortHelper.isManualSort(sortFlags) != SortHelper.isManualSort(flags);

    sortFlags = flags;
    sortSort = sort;

    if (always) {
      SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(ContextManager.getContext());
      if (publicPrefs != null) {
        Editor editor = publicPrefs.edit();
        if (editor != null) {
          editor.putInt(SortHelper.PREF_SORT_FLAGS, flags);
          editor.putInt(SortHelper.PREF_SORT_SORT, sort);
          editor.commit();
          TasksWidget.updateWidgets(ContextManager.getContext());
        }
      }
    }

    try {
      if (manualSettingChanged) toggleDragDrop(SortHelper.isManualSort(sortFlags));
      else setUpTaskList();
    } catch (IllegalStateException e) {
      // TODO: Fragment got detached somehow (rare)
    }
  }
  @Override
  public FilterListItem[] getFilters() {
    if (ContextManager.getContext() == null) {
      return null;
    }

    return prepareFilters(ContextManager.getContext());
  }
  @Override
  public FilterListItem[] getFilters() {
    if (ContextManager.getContext() == null || ContextManager.getContext().getResources() == null)
      return null;

    Resources r = ContextManager.getContext().getResources();
    return prepareFilters(r);
  }
  public static Spanned getUpdateComment(
      String actionCode,
      String user,
      String targetName,
      String message,
      String otherUser,
      String action,
      String linkColor,
      String fromView) {
    if (TextUtils.isEmpty(user)) {
      user = ContextManager.getString(R.string.ENA_no_user);
    }

    String userLink = linkify(user, linkColor);
    String targetNameLink = linkify(targetName, linkColor);
    String otherUserLink = linkify(otherUser, linkColor);

    int commentResource = 0;
    if (actionCode.equals(UPDATE_FRIENDS)) {
      commentResource = R.string.update_string_friends;
    } else if (actionCode.equals(UPDATE_REQUEST_FRIENDSHIP)) {
      commentResource = R.string.update_string_request_friendship;
    } else if (actionCode.equals(UPDATE_CONFIRMED_FRIENDSHIP)) {
      commentResource = R.string.update_string_confirmed_friendship;
    } else if (actionCode.equals(UPDATE_TASK_CREATED)) {
      if (fromView.equals(FROM_TAG_VIEW))
        commentResource = R.string.update_string_task_created_on_list;
      else commentResource = R.string.update_string_task_created;
    } else if (actionCode.equals(UPDATE_TASK_COMPLETED)) {
      commentResource = R.string.update_string_task_completed;
    } else if (actionCode.equals(UPDATE_TASK_UNCOMPLETED)) {
      commentResource = R.string.update_string_task_uncompleted;
    } else if (actionCode.equals(UPDATE_TASK_TAGGED) && !TextUtils.isEmpty(otherUser)) {
      if (fromView.equals(FROM_TAG_VIEW)) commentResource = R.string.update_string_task_tagged_list;
      else commentResource = R.string.update_string_task_tagged;
    } else if (actionCode.equals(UPDATE_TASK_ASSIGNED) && !TextUtils.isEmpty(otherUser)) {
      commentResource = R.string.update_string_task_assigned;
    } else if (actionCode.equals(UPDATE_TASK_COMMENT)) {
      if (fromView.equals(FROM_TASK_VIEW) || TextUtils.isEmpty(targetName))
        commentResource = R.string.update_string_default_comment;
      else commentResource = R.string.update_string_task_comment;
    } else if (actionCode.equals(UPDATE_TAG_COMMENT)) {
      if (fromView.equals(FROM_TAG_VIEW) || TextUtils.isEmpty(targetName))
        commentResource = R.string.update_string_default_comment;
      else commentResource = R.string.update_string_tag_comment;
    }

    if (commentResource == 0) {
      return Html.fromHtml(String.format("%s %s", userLink, action)); // $NON-NLS-1$
    }

    return Html.fromHtml(
        ContextManager.getString(
            commentResource, userLink, targetNameLink, message, otherUserLink));
  }
  /**
   * Invalidates and then revalidates the auth token for the currently logged in user Shouldn't be
   * called from the main thread--will block on network calls
   *
   * @return valid token on success, null on failure
   */
  public static synchronized String validateAuthToken(Context c, String token)
      throws GoogleTasksException {
    GoogleAccountManager accountManager = new GoogleAccountManager(ContextManager.getContext());

    if (testToken(token)) {
      return token;
    }

    // If fail, token may have expired -- get a new one and return that
    String accountName = Preferences.getStringValue(GtasksPreferenceService.PREF_USER_NAME);
    Account a = accountManager.getAccountByName(accountName);
    if (a == null) {
      throw new GoogleTasksException(
          c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found");
    }

    for (int i = 0; i < REVALIDATION_TRIES; i++) {
      accountManager.invalidateAuthToken(token);

      // try with notify-auth-failure = false
      AccountManagerFuture<Bundle> future =
          accountManager.manager.getAuthToken(a, GtasksInvoker.AUTH_TOKEN_TYPE, false, null, null);
      token = getTokenFromFuture(c, future);

      if (TOKEN_INTENT_RECEIVED.equals(token)) {
        return null;
      } else if (token != null && testToken(token)) {
        return token;
      }
    }

    throw new GoogleTasksException(
        c.getString(R.string.gtasks_error_authRefresh), "auth-token-refresh");
  }
Exemple #6
0
  /**
   * Deal with a synchronization exception. If requested, will show an error to the user (unless
   * synchronization is happening in background)
   *
   * @param context
   * @param tag error tag
   * @param e exception
   * @param showError whether to display a dialog
   */
  protected void handleException(String tag, Exception e, boolean displayError) {
    // TODO: When Crittercism supports it, report error to them
    final Context context = ContextManager.getContext();
    getUtilities().setLastError(e.toString());

    String message = null;

    // occurs when application was closed
    if (e instanceof IllegalStateException) {
      exceptionService.reportError(tag + "-caught", e); // $NON-NLS-1$
    }

    // occurs when network error
    else if (e instanceof IOException) {
      exceptionService.reportError(tag + "-io", e); // $NON-NLS-1$
      message = context.getString(R.string.SyP_ioerror);
    }

    // unhandled error
    else {
      message = context.getString(R.string.DLG_error, e.toString());
      exceptionService.reportError(tag + "-unhandled", e); // $NON-NLS-1$
    }

    if (displayError && context instanceof Activity && message != null) {
      DialogUtilities.okDialog((Activity) context, message, null);
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ContextManager.setContext(this);
    addPreferencesFromResource(getPreferenceResource());
  }
Exemple #8
0
  /**
   * Schedules alarms for a single task
   *
   * @param shouldPerformPropertyCheck whether to check if task has requisite properties
   */
  @SuppressWarnings("nls")
  private void scheduleAlarm(Metadata alarm) {
    if (alarm == null) return;

    long taskId = alarm.getValue(Metadata.TASK);
    int type = ReminderService.TYPE_ALARM;

    Context context = ContextManager.getContext();
    Intent intent = new Intent(context, Notifications.class);
    intent.setType("ALARM" + Long.toString(taskId)); // $NON-NLS-1$
    intent.setAction(Integer.toString(type));
    intent.putExtra(Notifications.ID_KEY, taskId);
    intent.putExtra(Notifications.TYPE_KEY, type);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    long time = alarm.getValue(AlarmFields.TIME);
    if (time == 0 || time == NO_ALARM) am.cancel(pendingIntent);
    else if (time > DateUtilities.now()) {
      if (Constants.DEBUG)
        Log.e("Astrid", "Alarm (" + taskId + ", " + type + ") set for " + new Date(time));
      am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    }
  }
    @Override
    public Void visitLong(Property<Long> property, UpgradeVisitorContainer<?> data) {
      long value = data.cursor.getLong(data.columnIndex);

      // special handling for due date
      if (property == Task.DUE_DATE) {
        long preferredDueDate =
            data.cursor.getLong(data.cursor.getColumnIndex(LegacyTaskModel.PREFERRED_DUE_DATE));
        if (value == 0) value = preferredDueDate;
        else if (preferredDueDate != 0) {
          // had both absolute and preferred due dates. write
          // preferred due date into notes field
          if (data.upgradeNotes == null) data.upgradeNotes = new StringBuilder();
          data.upgradeNotes.append(
              "Goal Deadline: "
                  + DateUtilities.getDateString(
                      ContextManager.getContext(), new Date(preferredDueDate)));
        }
      } else if (property == Task.REMINDER_PERIOD) {
        // old period was stored in seconds
        value *= 1000L;
      } else if (property == Task.COMPLETION_DATE) {
        // check if the task was actually completed
        int progress =
            data.cursor.getInt(data.cursor.getColumnIndex(LegacyTaskModel.PROGRESS_PERCENTAGE));
        if (progress < 100) value = 0;
      }

      data.model.setValue(property, value);
      Log.d(
          "upgrade",
          "wrote " + value + " to -> " + property + " of model id " + data.cursor.getLong(1));
      return null;
    }
  /** Create filter from new tag object */
  @SuppressWarnings("nls")
  public static FilterWithCustomIntent filterFromTag(
      Context context, Tag tag, Criterion criterion) {
    String listTitle = tag.tag + " (" + tag.count + ")";
    String title = context.getString(R.string.tag_FEx_name, tag.tag);
    QueryTemplate tagTemplate = tag.queryTemplate(criterion);
    ContentValues contentValues = new ContentValues();
    contentValues.put(Metadata.KEY.name, TagService.KEY);
    contentValues.put(TagService.TAG.name, tag.tag);

    FilterWithCustomIntent filter =
        new FilterWithCustomIntent(listTitle, title, tagTemplate, contentValues);
    if (tag.count == 0) filter.color = Color.GRAY;

    filter.contextMenuLabels =
        new String[] {
          context.getString(R.string.tag_cm_rename), context.getString(R.string.tag_cm_delete)
        };
    filter.contextMenuIntents =
        new Intent[] {
          newTagIntent(context, RenameTagActivity.class, tag),
          newTagIntent(context, DeleteTagActivity.class, tag)
        };
    filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewActivity.class);
    Bundle extras = new Bundle();
    extras.putString(TagViewActivity.EXTRA_TAG_NAME, tag.tag);
    extras.putLong(TagViewActivity.EXTRA_TAG_REMOTE_ID, tag.remoteId);
    filter.customExtras = extras;

    return filter;
  }
 private FilterCategory filterFromTags(Tag[] tags, int name) {
   Filter[] filters = new Filter[tags.length];
   Context context = ContextManager.getContext();
   for (int i = 0; i < tags.length; i++)
     filters[i] = filterFromTag(context, tags[i], TaskCriteria.activeAndVisible());
   return new FilterCategory(context.getString(name), filters);
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    DependencyInjectionService.getInstance().inject(this);
    ContextManager.setContext(context);
    tagService = TagService.getInstance();

    Resources r = context.getResources();
    ArrayList<FilterListItem> list = new ArrayList<FilterListItem>();

    // --- header
    FilterListHeader tagsHeader = new FilterListHeader(context.getString(R.string.tag_FEx_header));
    list.add(tagsHeader);

    // --- untagged
    Filter untagged =
        new Filter(
            r.getString(R.string.tag_FEx_untagged),
            r.getString(R.string.tag_FEx_untagged),
            tagService.untaggedTemplate(),
            null);
    untagged.listingIcon = ((BitmapDrawable) r.getDrawable(R.drawable.filter_untagged)).getBitmap();
    list.add(untagged);

    addTags(list);

    // transmit filter list
    FilterListItem[] listAsArray = list.toArray(new FilterListItem[list.size()]);
    Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS);
    broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, listAsArray);
    broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, TagsPlugin.IDENTIFIER);
    context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
  }
  /** Move data from alert table into metadata table. */
  private void migrateAlarmsToMetadata() {
    Context context = ContextManager.getContext();

    if (!checkIfDatabaseExists(context, AlarmDatabase.NAME)) return;

    AlarmDatabase alarmsDatabase = new AlarmDatabase();
    DatabaseDao<TransitionalAlarm> dao =
        new DatabaseDao<TransitionalAlarm>(TransitionalAlarm.class, alarmsDatabase);

    TodorooCursor<TransitionalAlarm> cursor = dao.query(Query.select(TransitionalAlarm.PROPERTIES));
    try {
      if (cursor.getCount() == 0) return;

      Metadata metadata = new Metadata();
      metadata.setValue(Metadata.KEY, AlarmFields.METADATA_KEY);
      for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        long task = cursor.get(TransitionalAlarm.TASK);
        long time = cursor.get(TransitionalAlarm.TIME);

        metadata.setValue(Metadata.TASK, task);
        metadata.setValue(AlarmFields.TIME, time);
        metadata.setValue(AlarmFields.TYPE, AlarmFields.TYPE_SINGLE);
        metadataDao.createNew(metadata);
        metadata.clearValue(Metadata.ID);
      }
    } finally {
      cursor.close();
      alarmsDatabase.close();
    }
  }
Exemple #14
0
        @SuppressWarnings("nls")
        @Override
        public void onReceive(Context context, Intent intent) {
          System.err.println("TVA thug hustlin - ");

          if (!intent.hasExtra("tag_id")) return;
          System.err.println(
              Long.toString(tagData.getValue(TagData.REMOTE_ID))
                  + " VS "
                  + intent.getStringExtra("tag_id"));
          if (!Long.toString(tagData.getValue(TagData.REMOTE_ID))
              .equals(intent.getStringExtra("tag_id"))) return;

          runOnUiThread(
              new Runnable() {
                @Override
                public void run() {
                  System.err.println("REFRESH updates list pa-pa-pa");
                  refreshUpdatesList();
                }
              });
          refreshData(false, true);

          NotificationManager nm = new AndroidNotificationManager(ContextManager.getContext());
          nm.cancel(tagData.getValue(TagData.REMOTE_ID).intValue());
        }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new StartupService().onStartupApplication(this);
    ContextManager.setContext(this);

    PreferenceScreen screen = getPreferenceScreen();
    voiceInputAssistant = new VoiceInputAssistant(this);

    addPluginPreferences(screen);

    screen.getPreference(POWER_PACK_PREFERENCE).setEnabled(addOnService.hasPowerPack());

    final Resources r = getResources();
    // About pref
    Preference preference = screen.getPreference(ABOUT_PREFERENCE);
    preference.setTitle(r.getString(R.string.p_about));
    preference.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference p) {
            showAbout();
            return true;
          }
        });

    addDebugPreferences();

    addPreferenceListeners();
  }
Exemple #16
0
  /**
   * Schedules alarms for a single task
   *
   * @param shouldPerformPropertyCheck whether to check if task has requisite properties
   */
  public static void cancelNotifications(long taskId) {
    if (notificationManager == null)
      synchronized (Notifications.class) {
        if (notificationManager == null)
          notificationManager = new AndroidNotificationManager(ContextManager.getContext());
      }

    notificationManager.cancel((int) taskId);
  }
Exemple #17
0
 private ActFmSyncThread(List<ClientToServerMessage<?>> messageQueue, Object syncMonitor) {
   DependencyInjectionService.getInstance().inject(this);
   this.pendingMessages = messageQueue;
   this.pendingCallbacks =
       Collections.synchronizedMap(new HashMap<ClientToServerMessage<?>, SyncMessageCallback>());
   this.monitor = syncMonitor;
   this.syncMigration = Preferences.getBoolean(AstridNewSyncMigrator.PREF_SYNC_MIGRATION, false);
   this.notificationManager = new AndroidNotificationManager(ContextManager.getContext());
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    Resources r = context.getResources();
    ContextManager.setContext(context);

    FilterListItem[] list = prepareFilters(r);
    Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS);
    broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, list);
    context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
  }
 /** Create a legacy backup file */
 private String legacyBackup() {
   try {
     LegacyTasksXmlExporter exporter = new LegacyTasksXmlExporter(true);
     exporter.setContext(ContextManager.getContext());
     return exporter.exportTasks(LegacyTasksXmlExporter.getExportDirectory());
   } catch (Exception e) {
     // unable to create a backup before upgrading :(
     return null;
   }
 }
 private String getValidatedAuthToken() {
   String authToken = gtasksPreferenceService.getToken();
   try {
     authToken = GtasksTokenValidator.validateAuthToken(ContextManager.getContext(), authToken);
     if (authToken != null) gtasksPreferenceService.setToken(authToken);
   } catch (GoogleTasksException e) {
     authToken = null;
   }
   return authToken;
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    ContextManager.setContext(context);
    // if we aren't logged in, don't expose features
    if (!ProducteevUtilities.INSTANCE.isLoggedIn()) return;

    StoreObject[] dashboards = ProducteevDataService.getInstance().getDashboards();

    // If user does not have any dashboards, don't show this section at all
    if (dashboards.length == 0) return;

    FilterListHeader producteevHeader =
        new FilterListHeader(context.getString(R.string.producteev_FEx_header));

    long currentUserId = Preferences.getLong(ProducteevUtilities.PREF_USER_ID, -1);

    // load dashboards
    Filter[] dashboardFilters = new Filter[dashboards.length];
    for (int i = 0; i < dashboards.length; i++)
      dashboardFilters[i] =
          filterFromList(context, new ProducteevDashboard(dashboards[i]), currentUserId);
    FilterCategory producteevDashboards =
        new FilterCategory(context.getString(R.string.producteev_FEx_dashboard), dashboardFilters);

    // load responsible people, assigned by me
    TreeSet<ProducteevUser> people = loadResponsiblePeople(dashboards);
    Filter[] peopleByMeFilters = new Filter[people.size()];
    int index = 0;
    for (ProducteevUser person : people)
      peopleByMeFilters[index++] = filterUserAssignedByMe(context, person, currentUserId);
    FilterCategory producteevUsersByMeCategory =
        new FilterCategory(
            context.getString(R.string.producteev_FEx_responsible_byme), peopleByMeFilters);

    // load responsible people, assigned by others
    Filter[] peopleByOthersFilters = new Filter[people.size()];
    index = 0;
    for (ProducteevUser person : people)
      peopleByOthersFilters[index++] = filterUserAssignedByOthers(context, person, currentUserId);
    FilterCategory producteevUsersByOthersCategory =
        new FilterCategory(
            context.getString(R.string.producteev_FEx_responsible_byothers), peopleByOthersFilters);

    // transmit filter list
    FilterListItem[] list = new FilterListItem[4];
    list[0] = producteevHeader;
    list[1] = producteevDashboards;
    list[2] = producteevUsersByMeCategory;
    list[3] = producteevUsersByOthersCategory;
    Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS);
    broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, ProducteevUtilities.IDENTIFIER);
    broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, list);
    context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
  }
Exemple #22
0
  private void setWidgetSuppression(boolean suppress) {
    long date = suppress ? DateUtilities.now() : 0;
    TasksWidget.suppressUpdateFlag = date;

    if (date == 0) {
      Context context = ContextManager.getContext();
      if (context != null) {
        TasksWidget.updateWidgets(context);
      }
    }
  }
Exemple #23
0
 @Override
 public void onStart(final Intent intent, int startId) {
   ContextManager.setContext(this);
   new Thread(
           new Runnable() {
             @Override
             public void run() {
               startServiceInBackgroundThread(intent);
             }
           })
       .start();
 }
Exemple #24
0
  private void setupNotification() {
    try {
      NotificationCompat.Builder builder =
          new NotificationCompat.Builder(ContextManager.getContext());
      builder
          .setContentText(ContextManager.getString(R.string.actfm_sync_ongoing))
          .setContentTitle(ContextManager.getString(R.string.app_name))
          .setOngoing(true)
          .setSmallIcon(android.R.drawable.stat_notify_sync)
          .setContentIntent(
              PendingIntent.getActivity(
                  ContextManager.getContext().getApplicationContext(), 0, new Intent(), 0));

      notificationManager.notify(0, builder.getNotification());
      notificationId = 0;
    } catch (Exception e) {
      Log.e(ERROR_TAG, "Exception creating notification", e); // $NON-NLS-1$
    } catch (Error e) {
      Log.e(ERROR_TAG, "Error creating notification", e); // $NON-NLS-1$
    }
  }
Exemple #25
0
  /**
   * Show a new notification about the given task. Returns false if there was some sort of error or
   * the alarm should be disabled.
   */
  public boolean showTaskNotification(long id, int type, String reminder) {
    Task task;
    try {
      task =
          taskDao.fetch(
              id,
              Task.ID,
              Task.TITLE,
              Task.HIDE_UNTIL,
              Task.COMPLETION_DATE,
              Task.DUE_DATE,
              Task.DELETION_DATE,
              Task.REMINDER_FLAGS);
      if (task == null)
        throw new IllegalArgumentException("cound not find item with id"); // $NON-NLS-1$

    } catch (Exception e) {
      exceptionService.reportError("show-notif", e); // $NON-NLS-1$
      return false;
    }

    // you're done - don't sound, do delete
    if (task.isCompleted() || task.isDeleted()) return false;

    // it's hidden - don't sound, don't delete
    if (task.isHidden() && type == ReminderService.TYPE_RANDOM) return true;

    // task due date was changed, but alarm wasn't rescheduled
    if ((type == ReminderService.TYPE_DUE || type == ReminderService.TYPE_OVERDUE)
        && (!task.hasDueDate() || task.getValue(Task.DUE_DATE) > DateUtilities.now())) return true;

    // read properties
    String taskTitle = task.getValue(Task.TITLE);
    boolean nonstopMode = task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_MODE_NONSTOP);
    boolean ringFiveMode = task.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_MODE_FIVE);
    int ringTimes = nonstopMode ? -1 : (ringFiveMode ? 5 : 1);

    // update last reminder time
    task.setValue(Task.REMINDER_LAST, DateUtilities.now());
    taskDao.saveExisting(task);

    Context context = ContextManager.getContext();
    String title = context.getString(R.string.app_name);
    String text = reminder + " " + taskTitle; // $NON-NLS-1$

    Intent notifyIntent = new Intent(context, NotificationActivity.class);
    notifyIntent.setAction("NOTIFY" + id); // $NON-NLS-1$
    notifyIntent.putExtra(NotificationActivity.TOKEN_ID, id);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

    showNotification((int) id, notifyIntent, type, title, text, ringTimes);
    return true;
  }
  protected void onTaskDelete(Task task) {
    decrementFilterCount();

    Activity a = getActivity();
    if (a instanceof AstridActivity) {
      AstridActivity activity = (AstridActivity) a;
      TaskEditFragment tef = activity.getTaskEditFragment();
      if (tef != null) {
        if (task.getId() == tef.model.getId()) tef.discardButtonClick();
      }
    }
    TimerPlugin.updateTimer(ContextManager.getContext(), task, false);
  }
Exemple #27
0
  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    try {
      ContextManager.setContext(context);
      super.onUpdate(context, appWidgetManager, appWidgetIds);

      // Start in service to prevent Application Not Responding timeout
      updateWidgets(context);
    } catch (Exception e) {
      Log.e("astrid-update-widget", "widget update error", e); // $NON-NLS-1$ //$NON-NLS-2$
    }
  }
  /**
   * Move data from tags tables into metadata table. We do this by looping through both the tags and
   * tagTaskMap databases, reading data from both and adding to the Metadata table. This way, we are
   * able to do everything in one pass without loading too much into memory
   */
  @SuppressWarnings("nls")
  private void migrateTagsToMetadata() {
    Context context = ContextManager.getContext();

    if (!checkIfDatabaseExists(context, tagsTable) || !checkIfDatabaseExists(context, tagTaskTable))
      return;

    SQLiteDatabase tagsDb =
        new Astrid2UpgradeHelper(context, tagsTable, null, 1).getReadableDatabase();
    SQLiteDatabase tagTaskDb =
        new Astrid2UpgradeHelper(context, tagTaskTable, null, 1).getReadableDatabase();

    Cursor tagCursor =
        tagsDb.rawQuery("SELECT _id, name FROM " + tagsTable + " ORDER BY _id ASC", null);
    Cursor mapCursor = null;
    try {
      mapCursor =
          tagTaskDb.rawQuery("SELECT tag, task FROM " + tagTaskTable + " ORDER BY tag ASC", null);
      if (tagCursor.getCount() == 0) return;

      Metadata metadata = new Metadata();
      metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY);
      long tagId = -1;
      String tag = null;
      for (mapCursor.moveToFirst(); !mapCursor.isAfterLast(); mapCursor.moveToNext()) {
        long mapTagId = mapCursor.getLong(0);

        while (mapTagId > tagId && !tagCursor.isLast()) {
          tagCursor.moveToNext();
          tagId = tagCursor.getLong(0);
          tag = null;
        }

        if (mapTagId == tagId) {
          if (tag == null) tag = tagCursor.getString(1);
          long task = mapCursor.getLong(1);
          metadata.setValue(Metadata.TASK, task);
          metadata.setValue(Metadata.KEY, TaskToTagMetadata.KEY);
          metadata.setValue(TaskToTagMetadata.TAG_NAME, tag);
          metadataDao.createNew(metadata);
          metadata.clearValue(Metadata.ID);
        }
      }
    } finally {
      tagCursor.close();
      if (mapCursor != null) mapCursor.close();
      tagsDb.close();
      tagTaskDb.close();
    }
  }
  @Override
  public void onReceive(Context context, Intent intent) {
    ContextManager.setContext(context);
    DependencyInjectionService.getInstance().inject(this);
    long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1);
    if (taskId == -1) return;

    Task task = PluginServices.getTaskService().fetchById(taskId, Task.PROPERTIES);
    if (task == null || !task.isCompleted()) return;

    String recurrence = task.getValue(Task.RECURRENCE);
    if (recurrence != null && recurrence.length() > 0) {
      long newDueDate;
      try {
        newDueDate = computeNextDueDate(task, recurrence);
        if (newDueDate == -1) return;
      } catch (ParseException e) {
        PluginServices.getExceptionService().reportError("repeat-parse", e); // $NON-NLS-1$
        return;
      }

      StatisticsService.reportEvent(StatisticsConstants.V2_TASK_REPEAT);

      long oldDueDate = task.getValue(Task.DUE_DATE);
      long repeatUntil = task.getValue(Task.REPEAT_UNTIL);

      boolean repeatFinished = repeatUntil > 0 && newDueDate >= repeatUntil;
      if (repeatFinished) {
        Intent repeatFinishedIntent =
            new Intent(AstridApiConstants.BROADCAST_EVENT_TASK_REPEAT_FINISHED);
        repeatFinishedIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId());
        repeatFinishedIntent.putExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, oldDueDate);
        repeatFinishedIntent.putExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, newDueDate);
        context.sendOrderedBroadcast(repeatFinishedIntent, null);
        return;
      }

      rescheduleTask(task, newDueDate);

      // send a broadcast
      Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_TASK_REPEATED);
      broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId());
      broadcastIntent.putExtra(AstridApiConstants.EXTRAS_OLD_DUE_DATE, oldDueDate);
      broadcastIntent.putExtra(AstridApiConstants.EXTRAS_NEW_DUE_DATE, newDueDate);
      context.sendOrderedBroadcast(broadcastIntent, null);
      Flags.set(Flags.REFRESH);
      return;
    }
  }
 public void configureMicrophoneButton(final Fragment fragment, final int prompt) {
   if (Preferences.getBoolean(R.string.p_voiceInputEnabled, true)
       && VoiceRecognizer.voiceInputAvailable(ContextManager.getContext())) {
     voiceButton.setVisibility(View.VISIBLE);
     voiceButton.setOnClickListener(
         new OnClickListener() {
           @Override
           public void onClick(View v) {
             startVoiceRecognitionActivity(fragment, prompt);
           }
         });
   } else {
     voiceButton.setVisibility(View.GONE);
   }
 }