List of usage examples for android.content ContentUris withAppendedId
public static Uri withAppendedId(Uri contentUri, long id)
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java
private void saveBookmarkIfNeeded() { try {/*from ww w. j a v a2 s . c o m*/ if (isPodcast()) { long pos = position(); long bookmark = getBookmark(); long duration = duration(); if ((pos < bookmark && (pos + 10000) > bookmark) || (pos > bookmark && (pos - 10000) < bookmark)) { // The existing bookmark is close to the current // position, so don't update it. return; } if (pos < 15000 || (pos + 10000) > duration) { // if we're near the start or end, clear the bookmark pos = 0; } // write 'pos' to the bookmark field ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Media.BOOKMARK, pos); Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX)); getContentResolver().update(uri, values, null, null); } } catch (SQLiteException ex) { } }
From source file:com.colorchen.qbase.utils.FileUtil.java
@TargetApi(19) public static String getPathFromUri(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; }/* w w w . j a va 2 s .com*/ } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return ""; }
From source file:com.android.mms.ui.ComposeMessageActivity.java
private void editSmsMessageItem(MessageItem msgItem) { // When the message being edited is the only message in the conversation, the delete // below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a // thread contains no messages and silently deletes the thread. Meanwhile, the mConversation // object still holds onto the old thread_id and code thinks there's a backing thread in // the DB when it really has been deleted. Here we try and notice that situation and // clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll // create a new thread if necessary. synchronized (mConversation) { if (mConversation.getMessageCount() <= 1) { mConversation.clearThreadId(); MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE); }/*ww w . j av a2s.c om*/ } // Delete the old undelivered SMS and load its content. Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId); SqliteWrapper.delete(ComposeMessageActivity.this, mContentResolver, uri, null, null); mWorkingMessage.setText(msgItem.mBody); }
From source file:cn.suishen.email.activity.MessageViewFragmentBase.java
/** * Reload the UI from a provider cursor. {@link LoadMessageTask#onSuccess} calls it. * * Update the header views, and start loading the body. * * @param message A copy of the message loaded from the database * @param okToFetch If true, and message is not fully loaded, it's OK to fetch from * the network. Use false to prevent looping here. *//*from w w w .ja va 2s . com*/ protected void reloadUiFromMessage(Message message, boolean okToFetch) { mMessage = message; mAccountId = message.mAccountKey; mMessageObserver.register(ContentUris.withAppendedId(Message.CONTENT_URI, mMessage.mId)); updateHeaderView(mMessage); // Handle partially-loaded email, as follows: // 1. Check value of message.mFlagLoaded // 2. If != LOADED, ask controller to load it // 3. Controller callback (after loaded) should trigger LoadBodyTask & LoadAttachmentsTask // 4. Else start the loader tasks right away (message already loaded) if (okToFetch && message.mFlagLoaded != Message.FLAG_LOADED_COMPLETE) { mControllerCallback.getWrappee().setWaitForLoadMessageId(message.mId); mController.loadMessageForView(message.mId); } else { Address[] fromList = Address.unpack(mMessage.mFrom); boolean autoShowImages = false; for (Address sender : fromList) { String email = sender.getAddress(); if (shouldShowImagesFor(email)) { autoShowImages = true; break; } } mControllerCallback.getWrappee().setWaitForLoadMessageId(Message.NO_MESSAGE); // Ask for body new LoadBodyTask(message.mId, autoShowImages).executeParallel(); } }
From source file:com.android.exchange.adapter.EmailSyncAdapter.java
@Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); if (getSyncKey().equals("0")) { return false; }//from w w w. j a va 2s . c o m // Never upsync from these folders if (mMailbox.mType == Mailbox.TYPE_DRAFTS || mMailbox.mType == Mailbox.TYPE_OUTBOX) { return false; } // This code is split out for unit testing purposes boolean firstCommand = sendDeletedItems(s, mDeletedIdList, true); if (!mFetchRequestList.isEmpty()) { // Add FETCH commands for messages that need a body (i.e. we didn't find it during // our earlier sync; this happens only in EAS 2.5 where the body couldn't be found // after parsing the message's MIME data) if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } for (FetchRequest req : mFetchRequestList) { s.start(Tags.SYNC_FETCH).data(Tags.SYNC_SERVER_ID, req.serverId).end(); } } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items Cursor c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { ContentValues cv = new ContentValues(); while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // Keep going if there's no serverId String serverId = currentCursor.getString(UPDATES_SERVER_ID_COLUMN); if (serverId == null) { continue; } boolean flagChange = false; boolean readChange = false; long mailbox = currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN); // If the message is now in the trash folder, it has been deleted by the user if (mailbox == trashMailboxId) { if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); // Mark the message as moved (so the copy will be deleted if/when the server // version is synced) int flags = c.getInt(Message.LIST_FLAGS_COLUMN); cv.put(MessageColumns.FLAGS, flags | EasSyncService.MESSAGE_FLAG_MOVED_MESSAGE); cr.update(ContentUris.withAppendedId(Message.CONTENT_URI, id), cv, null, null); continue; } else if (mailbox != c.getLong(Message.LIST_MAILBOX_KEY_COLUMN)) { // The message has moved to another mailbox; add a request for this // Note: The Sync command doesn't handle moving messages, so we need // to handle this as a "request" (similar to meeting response and // attachment load) mService.addRequest(new MessageMoveRequest(id, mailbox)); // Regardless of other changes that might be made, we don't want to indicate // that this message has been updated until the move request has been // handled (without this, a crash between the flag upsync and the move // would cause the move to be lost) mUpdatedIdList.remove(id); } // We can only send flag changes to the server in 12.0 or later int flag = 0; if (mService.mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); if (read != c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (firstCommand) { s.start(Tags.SYNC_COMMANDS); firstCommand = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1 * WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!firstCommand) { s.end(); // SYNC_COMMANDS } return false; }
From source file:com.chen.mail.utils.NotificationUtils.java
private static Bitmap getContactIcon(final Context context, final String displayName, final String senderAddress, final Folder folder) { if (senderAddress == null) { return null; }//from w ww . ja v a 2 s. c om Bitmap icon = null; final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress })); // Get the ideal size for this icon. final Resources res = context.getResources(); final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (contactIds != null) { for (final long id : contactIds) { final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id); final Uri photoUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY); final Cursor cursor = context.getContentResolver().query(photoUri, new String[] { Photo.PHOTO }, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { final byte[] data = cursor.getBlob(0); if (data != null) { icon = BitmapFactory.decodeStream(new ByteArrayInputStream(data)); if (icon != null && icon.getHeight() < idealIconHeight) { // We should scale this image to fit the intended size icon = Bitmap.createScaledBitmap(icon, idealIconWidth, idealIconHeight, true); } if (icon != null) { break; } } } } finally { cursor.close(); } } } } if (icon == null) { // Make a colorful tile! final ImageCanvas.Dimensions dimensions = new ImageCanvas.Dimensions(idealIconWidth, idealIconHeight, ImageCanvas.Dimensions.SCALE_ONE); icon = new LetterTileProvider(context).getLetterTile(dimensions, displayName, senderAddress); } if (icon == null) { // Icon should be the default mail icon. icon = getDefaultNotificationIcon(context, folder, false /* single new message */); } return icon; }
From source file:com.indeema.mail.utils.NotificationUtils.java
private static Bitmap getContactIcon(final Context context, final String displayName, final String senderAddress, final Folder folder) { if (senderAddress == null) { return null; }//w w w . j a va2s . c o m Bitmap icon = null; final List<Long> contactIds = findContacts(context, Arrays.asList(new String[] { senderAddress })); // Get the ideal size for this icon. final Resources res = context.getResources(); final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (contactIds != null) { for (final long id : contactIds) { final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id); final Uri photoUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY); final Cursor cursor = context.getContentResolver().query(photoUri, new String[] { Photo.PHOTO }, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { final byte[] data = cursor.getBlob(0); if (data != null) { icon = BitmapFactory.decodeStream(new ByteArrayInputStream(data)); if (icon != null && icon.getHeight() < idealIconHeight) { // We should scale this image to fit the intended size icon = Bitmap.createScaledBitmap(icon, idealIconWidth, idealIconHeight, true); } if (icon != null) { break; } } } } finally { cursor.close(); } } } } if (icon == null) { // Make a colorful tile! final Dimensions dimensions = new Dimensions(idealIconWidth, idealIconHeight, Dimensions.SCALE_ONE); icon = new LetterTileProvider(context).getLetterTile(dimensions, displayName, senderAddress); } if (icon == null) { // Icon should be the default mail icon. icon = getDefaultNotificationIcon(context, folder, false /* single new message */); } return icon; }
From source file:com.android.exchange.SyncManager.java
/** * See if we need to change the syncInterval for any of our PIM mailboxes based on changes * to settings in the AccountManager (sync settings). * This code is called 1) when SyncManager starts, and 2) when SyncManager is running and there * are changes made (this is detected via a SyncStatusObserver) *//*w ww . j av a 2s . c o m*/ private void updatePIMSyncSettings(Account providerAccount, int mailboxType, String authority) { ContentValues cv = new ContentValues(); long mailboxId = Mailbox.findMailboxOfType(this, providerAccount.mId, mailboxType); // Presumably there is one, but if not, it's ok. Just move on... if (mailboxId != Mailbox.NO_MAILBOX) { // Create an AccountManager style Account android.accounts.Account acct = new android.accounts.Account(providerAccount.mEmailAddress, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE); // Get the mailbox; this happens rarely so it's ok to get it all Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mailboxId); if (mailbox == null) return; int syncInterval = mailbox.mSyncInterval; // If we're syncable, look further... if (ContentResolver.getIsSyncable(acct, authority) > 0) { // If we're supposed to sync automatically (push), set to push if it's not if (ContentResolver.getSyncAutomatically(acct, authority)) { if (syncInterval == Mailbox.CHECK_INTERVAL_NEVER || syncInterval > 0) { log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": push"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); } // If we're NOT supposed to push, and we're not set up that way, change it } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If not, set it to never check } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) { log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": manual"); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER); } // If we've made a change, update the Mailbox, and kick if (cv.containsKey(MailboxColumns.SYNC_INTERVAL)) { mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null); kick("sync settings change"); } } }
From source file:com.android.calendar.EventInfoFragment.java
private boolean saveEventColor() { if (mCurrentColor == mOriginalColor) { return false; }//ww w . j a va 2 s . co m ContentValues values = new ContentValues(); if (mCurrentColor != mCalendarColor) { values.put(Events.EVENT_COLOR_KEY, mCurrentColorKey); } else { values.put(Events.EVENT_COLOR_KEY, NO_EVENT_COLOR); } Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId); mHandler.startUpdate(mHandler.getNextToken(), null, uri, values, null, null, Utils.UNDO_DELAY); return true; }
From source file:com.android.exchange.SyncManager.java
/** * Compare our account list (obtained from EmailProvider) with the account list owned by * AccountManager. If there are any orphans (an account in one list without a corresponding * account in the other list), delete the orphan, as these must remain in sync. * * Note that the duplication of account information is caused by the Email application's * incomplete integration with AccountManager. * * This function may not be called from the main/UI thread, because it makes blocking calls * into the account manager./* w w w .ja v a 2s. co m*/ * * @param context The context in which to operate * @param cachedEasAccounts the exchange provider accounts to work from * @param accountManagerAccounts The account manager accounts to work from * @param blockExternalChanges FOR TESTING ONLY - block backups, security changes, etc. * @param resolver the content resolver for making provider updates (injected for testability) */ /* package */ static void reconcileAccountsWithAccountManager(Context context, List<Account> cachedEasAccounts, android.accounts.Account[] accountManagerAccounts, boolean blockExternalChanges, ContentResolver resolver) { // First, look through our cached EAS Accounts (from EmailProvider) to make sure there's a // corresponding AccountManager account boolean accountsDeleted = false; for (Account providerAccount : cachedEasAccounts) { String providerAccountName = providerAccount.mEmailAddress; boolean found = false; for (android.accounts.Account accountManagerAccount : accountManagerAccounts) { if (accountManagerAccount.name.equalsIgnoreCase(providerAccountName)) { found = true; break; } } if (!found) { if ((providerAccount.mFlags & Account.FLAGS_INCOMPLETE) != 0) { log("Account reconciler noticed incomplete account; ignoring"); continue; } // This account has been deleted in the AccountManager! alwaysLog("Account deleted in AccountManager; deleting from provider: " + providerAccountName); // TODO This will orphan downloaded attachments; need to handle this resolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI, providerAccount.mId), null, null); accountsDeleted = true; } } // Now, look through AccountManager accounts to make sure we have a corresponding cached EAS // account from EmailProvider for (android.accounts.Account accountManagerAccount : accountManagerAccounts) { String accountManagerAccountName = accountManagerAccount.name; boolean found = false; for (Account cachedEasAccount : cachedEasAccounts) { if (cachedEasAccount.mEmailAddress.equalsIgnoreCase(accountManagerAccountName)) { found = true; } } if (!found) { // This account has been deleted from the EmailProvider database alwaysLog("Account deleted from provider; deleting from AccountManager: " + accountManagerAccountName); // Delete the account AccountManagerFuture<Boolean> blockingResult = AccountManager.get(context) .removeAccount(accountManagerAccount, null, null); try { // Note: All of the potential errors from removeAccount() are simply logged // here, as there is nothing to actually do about them. blockingResult.getResult(); } catch (OperationCanceledException e) { Log.w(Email.LOG_TAG, e.toString()); } catch (AuthenticatorException e) { Log.w(Email.LOG_TAG, e.toString()); } catch (IOException e) { Log.w(Email.LOG_TAG, e.toString()); } accountsDeleted = true; } } // If we changed the list of accounts, refresh the backup & security settings if (!blockExternalChanges && accountsDeleted) { AccountBackupRestore.backupAccounts(context); SecurityPolicy.getInstance(context).reducePolicies(); Email.setNotifyUiAccountsChanged(true); } }