List of usage examples for android.content ContentUris withAppendedId
public static Uri withAppendedId(Uri contentUri, long id)
From source file:com.indeema.emailcommon.utility.AttachmentUtilities.java
/** * Save the attachment to its final resting place (cache or sd card) *///from w w w .j a v a2s . c o m public static void saveAttachment(Context context, InputStream in, Attachment attachment) { Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId); ContentValues cv = new ContentValues(); long attachmentId = attachment.mId; long accountId = attachment.mAccountKey; String contentUri = null; long size; try { ContentResolver resolver = context.getContentResolver(); if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) { Uri attUri = getAttachmentUri(accountId, attachmentId); size = copyFile(in, resolver.openOutputStream(attUri)); contentUri = attUri.toString(); } else if (Utility.isExternalStorageMounted()) { if (attachment.mFileName == null) { // TODO: This will prevent a crash but does not surface the underlying problem // to the user correctly. LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId); throw new IOException("Can't save an attachment with no name"); } File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = Utility.createUniqueFile(downloads, attachment.mFileName); size = copyFile(in, new FileOutputStream(file)); String absolutePath = file.getAbsolutePath(); // Although the download manager can scan media files, scanning only happens // after the user clicks on the item in the Downloads app. So, we run the // attachment through the media scanner ourselves so it gets added to // gallery / music immediately. MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null); DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName, false /* do not use media scanner */, attachment.mMimeType, absolutePath, size, true /* show notification */); contentUri = dm.getUriForDownloadedFile(id).toString(); } else { LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?"); throw new IOException(); } // Update the attachment cv.put(AttachmentColumns.SIZE, size); cv.put(AttachmentColumns.CONTENT_URI, contentUri); cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED); } catch (IOException e) { // Handle failures here... cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED); } context.getContentResolver().update(uri, cv, null, null); // If this is an inline attachment, update the body if (contentUri != null && attachment.mContentId != null) { Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey); if (body != null && body.mHtmlContent != null) { cv.clear(); String html = body.mHtmlContent; String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\""; String srcContentUri = " src=\"" + contentUri + "\""; html = html.replaceAll(contentIdRe, srcContentUri); cv.put(BodyColumns.HTML_CONTENT, html); context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv, null, null); } } }
From source file:com.android.app.MediaPlaybackActivity.java
public boolean onLongClick(View view) { CharSequence title = null;/*from ww w . j a va 2s . c o m*/ String mime = null; String query = null; String artist; String album; String song; long audioid; try { artist = mService.getArtistName(); album = mService.getAlbumName(); song = mService.getTrackName(); audioid = mService.getAudioId(); } catch (RemoteException ex) { return true; } catch (NullPointerException ex) { // we might not actually have the service yet return true; } if (MediaStore.UNKNOWN_STRING.equals(album) && MediaStore.UNKNOWN_STRING.equals(artist) && song != null && song.startsWith("recording")) { // not music return false; } if (audioid < 0) { return false; } Cursor c = MusicUtils.query(this, ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid), new String[] { MediaStore.Audio.Media.IS_MUSIC }, null, null, null); boolean ismusic = true; if (c != null) { if (c.moveToFirst()) { ismusic = c.getInt(0) != 0; } c.close(); } if (!ismusic) { return false; } boolean knownartist = (artist != null) && !MediaStore.UNKNOWN_STRING.equals(artist); boolean knownalbum = (album != null) && !MediaStore.UNKNOWN_STRING.equals(album); if (knownartist && view.equals(mArtistName.getParent())) { title = artist; query = artist; mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE; } else if (knownalbum && view.equals(mAlbumName.getParent())) { title = album; if (knownartist) { query = artist + " " + album; } else { query = album; } mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE; } else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) { if ((song == null) || MediaStore.UNKNOWN_STRING.equals(song)) { // A popup of the form "Search for null/'' using ..." is pretty // unhelpful, plus, we won't find any way to buy it anyway. return true; } title = song; if (knownartist) { query = artist + " " + song; } else { query = song; } mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it } else { throw new RuntimeException("shouldn't be here"); } title = getString(R.string.mediasearch, title); Intent i = new Intent(); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH); i.putExtra(SearchManager.QUERY, query); if (knownartist) { i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist); } if (knownalbum) { i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album); } i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song); i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime); startActivity(Intent.createChooser(i, title)); return true; }
From source file:com.granita.icloudcalsync.resource.LocalAddressBook.java
protected void populatePhoto(Contact c, ContentValues row) throws RemoteException { if (row.containsKey(Photo.PHOTO_FILE_ID)) { Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, c.getLocalID()), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try {//from w ww .java2s. com @Cleanup AssetFileDescriptor fd = providerClient.openAssetFile(photoUri, "r"); @Cleanup InputStream is = fd.createInputStream(); c.setPhoto(IOUtils.toByteArray(is)); } catch (IOException ex) { Log.w(TAG, "Couldn't read high-res contact photo", ex); } } else c.setPhoto(row.getAsByteArray(Photo.PHOTO)); }
From source file:com.gecq.musicwave.cache.ImageCache.java
/** * Used to fetch the artwork for an album locally from the user's device * * @param context The {@link Context} to use * @param albumID The ID of the album to find artwork for * @return The artwork for an album/*w w w . ja v a 2 s .co m*/ */ public final Bitmap getArtworkFromFile(final Context context, final long albumId) { if (albumId < 0) { return null; } Bitmap artwork = null; waitUntilUnpaused(); try { final Uri uri = ContentUris.withAppendedId(mArtworkUri, albumId); final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor != null) { final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor); } } catch (final IllegalStateException e) { // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e); } catch (final FileNotFoundException e) { // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e); } catch (final OutOfMemoryError evict) { // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict); evictAll(); } return artwork; }
From source file:com.piusvelte.sonet.core.SonetService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else//from w w w . j a va2 s .c o m putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(SonetService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(SonetService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(SonetService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(SonetService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Sonet.default_message_bg_color; int profile_bg_color = Sonet.default_message_bg_color; int friend_bg_color = Sonet.default_friend_bg_color; boolean icon = true; int status_count = Sonet.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(SonetService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Sonet.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(SonetService.this, widget, Sonet.INVALID_ACCOUNT_ID); } initAccountSettings(SonetService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(SonetService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(SonetService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(SonetService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(SonetService.this, 0, (Sonet .getPackageIntent(SonetService.this, SonetNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:at.bitfire.davdroid.resource.LocalCollection.java
/** Updates the locally-known ETag of a resource. */ public void updateETag(Resource res, String eTag) throws LocalStorageException { Log.d(TAG, "Setting ETag of local resource " + res.getName() + " to " + eTag); ContentValues values = new ContentValues(1); values.put(entryColumnETag(), eTag); try {//from ww w . ja v a2 s . c o m providerClient.update(ContentUris.withAppendedId(entriesURI(), res.getLocalID()), values, null, new String[] {}); } catch (RemoteException e) { throw new LocalStorageException(e); } }
From source file:com.akop.bach.fragment.xboxlive.AchievementsFragment.java
@Override public void onImageReady(long id, Object param, Bitmap bmp) { super.onImageReady(id, param, bmp); getActivity().getContentResolver().notifyChange(ContentUris.withAppendedId(Achievements.CONTENT_URI, id), null);//w w w. j av a 2s. c om }
From source file:com.android.email.LegacyConversions.java
/** * Add a single attachment part to the message * * This will skip adding attachments if they are already found in the attachments table. * The heuristic for this will fail (false-positive) if two identical attachments are * included in a single POP3 message./*from w ww . j a v a2s . c om*/ * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments * position within the list of multipart/mixed elements. This would make every POP3 attachment * unique, and might also simplify the code (since we could just look at the positions, and * ignore the filename, etc.) * * TODO: Take a closer look at encoding and deal with it if necessary. * * @param context a context for file operations * @param localMessage the attachments will be built against this message * @param part a single attachment part from POP or IMAP * @param upgrading true if upgrading a local account - handle attachments differently * @throws IOException */ private static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part, boolean upgrading) throws MessagingException, IOException { Attachment localAttachment = new Attachment(); // Transfer fields from mime format to provider format String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String name = MimeUtility.getHeaderParameter(contentType, "name"); if (name == null) { String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition()); name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } // Select the URI for the new attachments. For attachments downloaded by the legacy // IMAP/POP code, this is not determined yet, so is null (it will be rewritten below, // or later, when the actual attachment file is created.) // // When upgrading older local accounts, the URI represents a local asset (e.g. a photo) // so we need to preserve the URI. // TODO This works for outgoing messages, where the URI does not change. May need // additional logic to handle the case of rewriting URI for received attachments. Uri contentUri = null; String contentUriString = null; if (upgrading) { Body body = part.getBody(); if (body instanceof LocalStore.LocalAttachmentBody) { LocalStore.LocalAttachmentBody localBody = (LocalStore.LocalAttachmentBody) body; contentUri = localBody.getContentUri(); if (contentUri != null) { contentUriString = contentUri.toString(); } } } // Find size, if available, via a number of techniques: long size = 0; if (upgrading) { // If upgrading a legacy account, the size must be recaptured from the data source if (contentUri != null) { Cursor metadataCursor = context.getContentResolver().query(contentUri, ATTACHMENT_META_COLUMNS_PROJECTION, null, null, null); if (metadataCursor != null) { try { if (metadataCursor.moveToFirst()) { size = metadataCursor.getInt(ATTACHMENT_META_COLUMNS_SIZE); } } finally { metadataCursor.close(); } } } // TODO: a downloaded legacy attachment - see if the above code works } else { // Incoming attachment: Try to pull size from disposition (if not downloaded yet) String disposition = part.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Long.parseLong(s); } } } // Get partId for unloaded IMAP attachments (if any) // This is only provided (and used) when we have structure but not the actual attachment String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA); String partId = partIds != null ? partIds[0] : null; localAttachment.mFileName = name; localAttachment.mMimeType = part.getMimeType(); localAttachment.mSize = size; // May be reset below if file handled localAttachment.mContentId = part.getContentId(); localAttachment.mContentUri = contentUriString; localAttachment.mMessageKey = localMessage.mId; localAttachment.mLocation = partId; localAttachment.mEncoding = "B"; // TODO - convert other known encodings if (DEBUG_ATTACHMENTS) { Log.d(Email.LOG_TAG, "Add attachment " + localAttachment); } // To prevent duplication - do we already have a matching attachment? // The fields we'll check for equality are: // mFileName, mMimeType, mContentId, mMessageKey, mLocation // NOTE: This will false-positive if you attach the exact same file, twice, to a POP3 // message. We can live with that - you'll get one of the copies. Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId); Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null); boolean attachmentFoundInDb = false; try { while (cursor.moveToNext()) { Attachment dbAttachment = new Attachment().restore(cursor); // We test each of the fields here (instead of in SQL) because they may be // null, or may be strings. if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName)) continue; if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType)) continue; if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId)) continue; if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation)) continue; // We found a match, so use the existing attachment id, and stop looking/looping attachmentFoundInDb = true; localAttachment.mId = dbAttachment.mId; if (DEBUG_ATTACHMENTS) { Log.d(Email.LOG_TAG, "Skipped, found db attachment " + dbAttachment); } break; } } finally { cursor.close(); } // Save the attachment (so far) in order to obtain an id if (!attachmentFoundInDb) { localAttachment.save(context); } // If an attachment body was actually provided, we need to write the file now if (!upgrading) { saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey); } if (localMessage.mAttachments == null) { localMessage.mAttachments = new ArrayList<Attachment>(); } localMessage.mAttachments.add(localAttachment); localMessage.mFlagAttachment = true; }
From source file:com.boko.vimusic.cache.ImageCache.java
/** * Used to fetch the artwork for an album locally from the user's device * /* www. j a va 2 s . c o m*/ * @param context * The {@link Context} to use * @param albumID * The ID of the album to find artwork for * @return The artwork for an album */ public final Bitmap getArtworkFromFile(final Context context, final String albumId) { if (albumId == null) { return null; } Bitmap artwork = null; waitUntilUnpaused(); try { final Uri uri = ContentUris.withAppendedId(mArtworkUri, Long.valueOf(albumId)); final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor != null) { final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor); } } catch (final IllegalStateException e) { // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e); } catch (final FileNotFoundException e) { // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e); } catch (final OutOfMemoryError evict) { // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict); evictAll(); } return artwork; }
From source file:com.andrew.apollo.cache.ImageCache.java
/** * Used to fetch the artwork for an album locally from the user's device * // w w w . j a v a2s .c om * @param context The {@link Context} to use * @param albumID The ID of the album to find artwork for * @return The artwork for an album */ public final Bitmap getArtworkFromFile(final Context context, final String albumId) { if (TextUtils.isEmpty(albumId)) { return null; } Bitmap artwork = null; while (mPauseDiskAccess) { // Pause for a moment } try { final Uri uri = ContentUris.withAppendedId(mArtworkUri, Long.valueOf(albumId)); final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); if (parcelFileDescriptor != null) { final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor); } } catch (final IllegalStateException e) { // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e); } catch (final FileNotFoundException e) { // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e); } catch (final OutOfMemoryError evict) { // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict); evictAll(); } return artwork; }