List of usage examples for android.content ContentUris withAppendedId
public static Uri withAppendedId(Uri contentUri, long id)
From source file:com.android.calendar.alerts.AlertService.java
/** * Processes the query results and bucketizes the alerts. * * @param highPriorityEvents This will contain future events, and concurrent events * that started recently (less than the interval DEPRIORITIZE_GRACE_PERIOD_MS). * @param mediumPriorityEvents This will contain concurrent events that started * more than DEPRIORITIZE_GRACE_PERIOD_MS ago. * @param lowPriorityEvents Will contain events that have ended. * @return Returns the number of new alerts to fire. If this is 0, it implies * a quiet update./*w ww . j a v a 2 s. c o m*/ */ static int processQuery(final Cursor alertCursor, final Context context, final long currentTime, ArrayList<NotificationInfo> highPriorityEvents, ArrayList<NotificationInfo> mediumPriorityEvents, ArrayList<NotificationInfo> lowPriorityEvents) { // Experimental reminder setting to only remind for events that have // been responded to with "yes" or "maybe". String skipRemindersPref = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_REMINDERS_RESPONDED, ""); // Skip no-response events if the "Skip Reminders" preference has the second option, // "If declined or not responded", is selected. // Note that by default, the first option will be selected, so this will be false. boolean remindRespondedOnly = skipRemindersPref .equals(context.getResources().getStringArray(R.array.preferences_skip_reminders_values)[1]); // Experimental reminder setting to silence reminders when they are // during the pre-defined quiet hours. boolean useQuietHours = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS, false); // Note that the start time may be either before or after the end time, // depending on whether quiet hours cross through midnight. int quietHoursStartHour = OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR; int quietHoursStartMinute = OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE; int quietHoursEndHour = OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR; int quietHoursEndMinute = OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE; if (useQuietHours) { quietHoursStartHour = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_START_HOUR, OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR); quietHoursStartMinute = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_START_MINUTE, OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE); quietHoursEndHour = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_END_HOUR, OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR); quietHoursEndMinute = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_END_MINUTE, OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE); } Time time = new Time(); ContentResolver cr = context.getContentResolver(); HashMap<Long, NotificationInfo> eventIds = new HashMap<Long, NotificationInfo>(); int numFired = 0; try { while (alertCursor.moveToNext()) { final long alertId = alertCursor.getLong(ALERT_INDEX_ID); final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID); final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES); final String eventName = alertCursor.getString(ALERT_INDEX_TITLE); final String description = alertCursor.getString(ALERT_INDEX_DESCRIPTION); final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION); final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS); final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED; final boolean responded = status != Attendees.ATTENDEE_STATUS_NONE && status != Attendees.ATTENDEE_STATUS_INVITED; final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN); final long endTime = alertCursor.getLong(ALERT_INDEX_END); final Uri alertUri = ContentUris.withAppendedId(CalendarAlerts.CONTENT_URI, alertId); final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME); boolean forceQuiet = false; if (useQuietHours) { // Quiet hours have been set. time.set(alarmTime); // Check whether the alarm will fire after the quiet hours // start time and/or before the quiet hours end time. boolean alarmAfterQuietHoursStart = (time.hour > quietHoursStartHour || (time.hour == quietHoursStartHour && time.minute >= quietHoursStartMinute)); boolean alarmBeforeQuietHoursEnd = (time.hour < quietHoursEndHour || (time.hour == quietHoursEndHour && time.minute <= quietHoursEndMinute)); // Check if quiet hours crosses through midnight, iff: // start hour is after end hour, or // start hour is equal to end hour, and start minute is // after end minute. // i.e. 22:30 - 06:45; 12:45 - 12:00 // 01:05 - 10:30; 05:00 - 05:30 boolean quietHoursCrossesMidnight = quietHoursStartHour > quietHoursEndHour || (quietHoursStartHour == quietHoursEndHour && quietHoursStartMinute > quietHoursEndMinute); if (quietHoursCrossesMidnight) { // Quiet hours crosses midnight. Alarm should be quiet // if it's after start time OR before end time. if (alarmAfterQuietHoursStart || alarmBeforeQuietHoursEnd) { forceQuiet = true; } } else { // Quiet hours doesn't cross midnight. Alarm should be // quiet if it's after start time AND before end time. if (alarmAfterQuietHoursStart && alarmBeforeQuietHoursEnd) { forceQuiet = true; } } } int state = alertCursor.getInt(ALERT_INDEX_STATE); final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0; // Use app local storage to keep track of fired alerts to fix problem of multiple // installed calendar apps potentially causing missed alarms. boolean newAlertOverride = false; if (AlertUtils.BYPASS_DB && ((currentTime - alarmTime) / MINUTE_MS < 1)) { // To avoid re-firing alerts, only fire if alarmTime is very recent. Otherwise // we can get refires for non-dismissed alerts after app installation, or if the // SharedPrefs was cleared too early. This means alerts that were timed while // the phone was off may show up silently in the notification bar. boolean alreadyFired = AlertUtils.hasAlertFiredInSharedPrefs(context, eventId, beginTime, alarmTime); if (!alreadyFired) { newAlertOverride = true; } } if (DEBUG) { StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("alertCursor result: alarmTime:").append(alarmTime).append(" alertId:") .append(alertId).append(" eventId:").append(eventId).append(" state: ").append(state) .append(" minutes:").append(minutes).append(" declined:").append(declined) .append(" responded:").append(responded).append(" beginTime:").append(beginTime) .append(" endTime:").append(endTime).append(" allDay:").append(allDay) .append(" alarmTime:").append(alarmTime).append(" forceQuiet:").append(forceQuiet); if (AlertUtils.BYPASS_DB) { msgBuilder.append(" newAlertOverride: " + newAlertOverride); } Log.d(TAG, msgBuilder.toString()); } ContentValues values = new ContentValues(); int newState = -1; boolean newAlert = false; // Uncomment for the behavior of clearing out alerts after the // events ended. b/1880369 // // if (endTime < currentTime) { // newState = CalendarAlerts.DISMISSED; // } else // Remove declined events boolean sendAlert = !declined; // Check for experimental reminder settings. if (remindRespondedOnly) { // If the experimental setting is turned on, then only send // the alert if you've responded to the event. sendAlert = sendAlert && responded; } if (sendAlert) { if (state == CalendarAlerts.STATE_SCHEDULED || newAlertOverride) { newState = CalendarAlerts.STATE_FIRED; numFired++; // If quiet hours are forcing the alarm to be silent, // keep newAlert as false so it will not make noise. if (!forceQuiet) { newAlert = true; } // Record the received time in the CalendarAlerts table. // This is useful for finding bugs that cause alarms to be // missed or delayed. values.put(CalendarAlerts.RECEIVED_TIME, currentTime); } } else { newState = CalendarAlerts.STATE_DISMISSED; } // Update row if state changed if (newState != -1) { values.put(CalendarAlerts.STATE, newState); state = newState; if (AlertUtils.BYPASS_DB) { AlertUtils.setAlertFiredInSharedPrefs(context, eventId, beginTime, alarmTime); } } if (state == CalendarAlerts.STATE_FIRED) { // Record the time posting to notification manager. // This is used for debugging missed alarms. values.put(CalendarAlerts.NOTIFY_TIME, currentTime); } // Write row to if anything changed if (values.size() > 0) cr.update(alertUri, values, null, null); if (state != CalendarAlerts.STATE_FIRED) { continue; } // TODO: Prefer accepted events in case of ties. NotificationInfo newInfo = new NotificationInfo(eventName, location, description, beginTime, endTime, eventId, allDay, newAlert); // Adjust for all day events to ensure the right bucket. Don't use the 1/4 event // duration grace period for these. long beginTimeAdjustedForAllDay = beginTime; String tz = null; if (allDay) { tz = TimeZone.getDefault().getID(); beginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, beginTime, tz); } // Handle multiple alerts for the same event ID. if (eventIds.containsKey(eventId)) { NotificationInfo oldInfo = eventIds.get(eventId); long oldBeginTimeAdjustedForAllDay = oldInfo.startMillis; if (allDay) { oldBeginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, oldInfo.startMillis, tz); } // Determine whether to replace the previous reminder with this one. // Query results are sorted so this one will always have a lower start time. long oldStartInterval = oldBeginTimeAdjustedForAllDay - currentTime; long newStartInterval = beginTimeAdjustedForAllDay - currentTime; boolean dropOld; if (newStartInterval < 0 && oldStartInterval > 0) { // Use this reminder if this event started recently dropOld = Math.abs(newStartInterval) < MIN_DEPRIORITIZE_GRACE_PERIOD_MS; } else { // ... or if this one has a closer start time. dropOld = Math.abs(newStartInterval) < Math.abs(oldStartInterval); } if (dropOld) { // This is a recurring event that has a more relevant start time, // drop other reminder in favor of this one. // // It will only be present in 1 of these buckets; just remove from // multiple buckets since this occurrence is rare enough that the // inefficiency of multiple removals shouldn't be a big deal to // justify a more complicated data structure. Expired events don't // have individual notifications so we don't need to clean that up. highPriorityEvents.remove(oldInfo); mediumPriorityEvents.remove(oldInfo); if (DEBUG) { Log.d(TAG, "Dropping alert for recurring event ID:" + oldInfo.eventId + ", startTime:" + oldInfo.startMillis + " in favor of startTime:" + newInfo.startMillis); } } else { // Skip duplicate reminders for the same event instance. continue; } } // TODO: Prioritize by "primary" calendar eventIds.put(eventId, newInfo); long highPriorityCutoff = currentTime - getGracePeriodMs(beginTime, endTime, allDay); if (beginTimeAdjustedForAllDay > highPriorityCutoff) { // High priority = future events or events that just started highPriorityEvents.add(newInfo); } else if (allDay && tz != null && DateUtils.isToday(beginTimeAdjustedForAllDay)) { // Medium priority = in progress all day events mediumPriorityEvents.add(newInfo); } else { lowPriorityEvents.add(newInfo); } } // TODO(cwren) add beginTime/startTime GlobalDismissManager.processEventIds(context, eventIds.keySet()); } finally { if (alertCursor != null) { alertCursor.close(); } } return numFired; }
From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java
protected boolean saveFeature() { if (mLayer == null) { Toast.makeText(this, R.string.error_layer_not_inited, Toast.LENGTH_SHORT).show(); return false; }/*from www. jav a 2 s .com*/ //create new row or modify existing List<Field> fields = mLayer.getFields(); ContentValues values = new ContentValues(); for (Field field : fields) { putFieldValue(values, field); } putGeometry(values); IGISApplication app = (IGISApplication) getApplication(); if (null == app) { throw new IllegalArgumentException("Not a IGISApplication"); } Uri uri = Uri.parse("content://" + app.getAuthority() + "/" + mLayer.getPath().getName()); boolean error; if (mFeatureId == NOT_FOUND) { // we need to get proper mFeatureId for new features first Uri result = getContentResolver().insert(uri, values); if (error = result == null) Toast.makeText(this, getText(R.string.error_db_insert), Toast.LENGTH_SHORT).show(); else mFeatureId = Long.parseLong(result.getLastPathSegment()); } else { Uri updateUri = ContentUris.withAppendedId(uri, mFeatureId); boolean valuesUpdated = getContentResolver().update(updateUri, values, null, null) == 1; if (error = !valuesUpdated) Toast.makeText(this, getText(R.string.error_db_update), Toast.LENGTH_SHORT).show(); } putAttaches(); putSign(); Intent data = new Intent(); data.putExtra(ConstantsUI.KEY_FEATURE_ID, mFeatureId); setResult(RESULT_OK, data); return !error; }
From source file:io.n7.calendar.caldav.CalDAVService.java
private void addEventOnServer(String uid, long id, CalDAV4jIf caldavif) throws Exception { VEvent ve = getEvFromDB(uid, id);/*from w w w. ja v a2 s .c om*/ if (ve != null) { caldavif.addEv(ve); //update DB to clear dirty ContentValues cv = new ContentValues(); cv.put(Events._SYNC_DIRTY, 0); cv.put(Events._SYNC_ID, uid); mCR.update(ContentUris.withAppendedId(EVENTS_URI, id), cv, null, null); } else //XXX this should never happen Log.e(TAG, "Could not find event with uid " + uid); }
From source file:com.android.providers.downloads.DownloadInfo.java
public Uri getMyDownloadsUri() { return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, mId); }
From source file:com.android.providers.downloads.DownloadInfo.java
public Uri getAllDownloadsUri() { return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, mId); }
From source file:io.n7.calendar.caldav.CalDAVService.java
private void removeLocalEvent(long id) { mCR.delete(ContentUris.withAppendedId(EVENTS_URI, id), null, null); Log.d(TAG, "removed ev " + id + " which got deleted on server"); }
From source file:com.jefftharris.passwdsafe.sync.MainActivity.java
/** Update the UI when the Google Drive account is changed */ private void updateGdriveAccount(Cursor cursor) { boolean haveCursor = (cursor != null); GuiUtils.setVisible(findViewById(R.id.gdrive_container), haveCursor); GuiUtils.setVisible(findViewById(R.id.gdrive_separator), haveCursor); if (haveCursor) { long id = cursor.getLong(PasswdSafeContract.Providers.PROJECTION_IDX_ID); String acct = PasswdSafeContract.Providers.getDisplayName(cursor); int freqVal = cursor.getInt(PasswdSafeContract.Providers.PROJECTION_IDX_SYNC_FREQ); ProviderSyncFreqPref freq = ProviderSyncFreqPref.freqValueOf(freqVal); itsGDrivePlayUri = ContentUris.withAppendedId(PasswdSafeContract.Providers.CONTENT_URI, id); TextView acctView = (TextView) findViewById(R.id.gdrive_acct); assert acctView != null; acctView.setText(acct);/*from w w w . j a v a 2 s . co m*/ View freqSpinLabel = findViewById(R.id.gdrive_interval_label); assert freqSpinLabel != null; Spinner freqSpin = (Spinner) findViewById(R.id.gdrive_interval); assert freqSpin != null; freqSpin.setSelection(freq.getDisplayIdx()); freqSpin.setEnabled(true); freqSpinLabel.setEnabled(true); } else { itsGDrivePlayUri = null; } }
From source file:com.openerp.support.calendar.OECalendar.java
/** * Delete events from OpenERP Mobile Calendar of MobilePhone/Device. * // w ww. j av a2s.c o m * @param calendar_Event_Id * : event id which'll be deleted. */ public void delete_CalendarEvent(int calendar_Event_Id) { long eventID = calendar_Event_Id; Uri deleteUri = null; deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID); int rows = context.getContentResolver().delete(deleteUri, null, null); }
From source file:com.kdao.cmpe235_project.UploadActivity.java
@SuppressLint("NewApi") private String getPath(Uri uri) throws URISyntaxException { final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19; String selection = null;//w ww . j a v a2s . c o m String[] selectionArgs = null; // Uri is different in versions after KITKAT (Android 4.4), we need to // deal with different Uris. if (needToCheckUri && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) { if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); return Environment.getExternalStorageDirectory() + "/" + split[1]; } else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); uri = ContentUris.withAppendedId(Uri.parse(LOCAL_FOLDER_PATH), Long.valueOf(id)); } else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("image".equals(type)) { uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } selection = "_id=?"; selectionArgs = new String[] { split[1] }; } } if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = null; try { cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } catch (Exception e) { } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
From source file:com.granita.tasks.TaskListFragment.java
@Override public boolean onFlingEnd(ListView v, View listElement, int pos, int direction) { long packedPos = mExpandableListView.getExpandableListPosition(pos); if (ExpandableListView.getPackedPositionType(packedPos) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { ExpandableListAdapter listAdapter = mExpandableListView.getExpandableListAdapter(); Cursor cursor = (Cursor) listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPos), ExpandableListView.getPackedPositionChild(packedPos)); if (cursor != null) { // TODO: for now we get the id of the task, not the instance, once we support recurrence we'll have to change that Long taskId = cursor.getLong(cursor.getColumnIndex(Instances.TASK_ID)); if (taskId != null) { boolean closed = cursor.getLong(cursor.getColumnIndex(Instances.IS_CLOSED)) > 0; String title = cursor.getString(cursor.getColumnIndex(Instances.TITLE)); // TODO: use the instance URI once we support recurrence Uri taskUri = ContentUris.withAppendedId(Tasks.getContentUri(mAuthority), taskId); if (direction == FlingDetector.RIGHT_FLING) { if (closed) { removeTask(taskUri, title); // we do not know for sure if the task has been removed since the user is asked for confirmation first, so return false return false; } else { return setCompleteTask(taskUri, title, true); }//from w w w .j a v a 2 s .c om } else if (direction == FlingDetector.LEFT_FLING) { if (closed) { return setCompleteTask(taskUri, title, false); } else { openTaskEditor(taskUri, cursor.getString(cursor.getColumnIndex(Instances.ACCOUNT_TYPE))); return false; } } } } } return false; }