private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) { Bitmap bm = null; byte[] art = null; String path = null; if (albumid < 0 && songid < 0) { throw new IllegalArgumentException("Must specify an album or a song id"); } try { if (albumid < 0) { Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart"); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } } else { Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } } } catch (FileNotFoundException ex) { // } return bm; }
/** * 直接根据uri 获取图片 * * @param context context * @param uri uri * @param cut 是否裁剪 * @param callBack 回调 */ public static void getImagePathFromURI( Context context, Uri uri, boolean cut, PhotoCallBack callBack) { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); String document_id = cursor.getString(0); document_id = document_id.substring(document_id.lastIndexOf(":") + 1); cursor.close(); cursor = context .getContentResolver() .query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[] {document_id}, null); cursor.moveToFirst(); String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); cursor.close(); if (callBack != null) { callBack.Success(path); } if (cut) { doCropPhoto(context, uri, new File(path)); } }
/** * Decode and sample down a bitmap from a file to the requested width and height. * * @param filename The full path of the file to decode * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that * are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromUri( Context context, Uri fileuri, int reqWidth, int reqHeight, ImageCache cache) { Bitmap bm = null; try { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream( context.getContentResolver().openInputStream(fileuri), null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bm = BitmapFactory.decodeStream( context.getContentResolver().openInputStream(fileuri), null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } return bm; }
public void save() { if (TextUtils.isEmpty(bookid)) throw new IllegalStateException("Please set the book id and try again"); ContentValues values = new ContentValues(); values.put("title", title); values.put("author", author); values.put("file", file); values.put("size", size); values.put("detail_image", detail_image); values.put("list_image", list_image); values.put("big_image", big_image); values.put("medium_image", medium_image); values.put("small_image", small_image); values.put("modified_date", modified_date); values.put("chapter", chapter); values.put("chapter_title", chapter_title); values.put("total_page", total_page); values.put("current_page", current_page); values.put("total_offset", total_offset); values.put("current_offset", current_offset); if (0 == context .getContentResolver() .update( MyContentProvider.BOOKMARK_CONTENT_URI, values, "bookid=?", new String[] {bookid})) { values.put("bookid", bookid); context.getContentResolver().insert(MyContentProvider.BOOKMARK_CONTENT_URI, values); } }
/** * For all accounts that require password expiration, put them in security hold and wipe their * data. * * @param context context * @return true if one or more accounts were wiped */ @VisibleForTesting /*package*/ static boolean wipeExpiredAccounts(Context context) { boolean result = false; Cursor c = context .getContentResolver() .query(Policy.CONTENT_URI, Policy.ID_PROJECTION, HAS_PASSWORD_EXPIRATION, null, null); if (c == null) { return false; } try { while (c.moveToNext()) { long policyId = c.getLong(Policy.ID_PROJECTION_COLUMN); long accountId = Policy.getAccountIdWithPolicyKey(context, policyId); if (accountId < 0) continue; Account account = Account.restoreAccountWithId(context, accountId); if (account != null) { // Mark the account as "on hold". setAccountHoldFlag(context, account, true); // Erase data Uri uri = EmailProvider.uiUri("uiaccountdata", accountId); context.getContentResolver().delete(uri, null, null); // Report one or more were found result = true; } } } finally { c.close(); } return result; }
/** 批量向歌单添加音乐 */ public static void addSongListToPlaylist( final Context context, final PlayList playlist, final ArrayList<Song> songs) { Cursor cur = context .getContentResolver() .query( MediaStore.Audio.Playlists.Members.getContentUri( "external", playlist.getmPlayListId()), null, null, null, MediaStore.Audio.Playlists.Members.TRACK + " ASC"); long count = 0; if (cur.moveToLast()) { count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK)); } cur.close(); ContentValues[] values = new ContentValues[songs.size()]; for (int i = 0; i < songs.size(); i++) { values[i] = new ContentValues(); values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1); values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(i).getmSongId()); } Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.getmPlayListId()); ContentResolver resolver = context.getContentResolver(); resolver.bulkInsert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); }
public static Bitmap getArtwork(Context context, long songId, long albumId, int targetSize) { if (albumId < 0 && songId < 0) { return null; } Bitmap bmp = null; try { ParcelFileDescriptor pfd = null; if (albumId < 0) { Uri uri = Uri.parse("content://media/external/audio/media/" + songId + "/albumart"); pfd = context.getContentResolver().openFileDescriptor(uri, "r"); } else { Uri uri = ContentUris.withAppendedId(AlbumArtUri, albumId); pfd = context.getContentResolver().openFileDescriptor(uri, "r"); } if (pfd == null) { return null; } bmp = decodeImage(pfd.getFileDescriptor(), targetSize); pfd.close(); } catch (Exception e) { e.printStackTrace(); } return bmp; }
private static Cursor getCursorForConstruction(Context context, long contactId, int queryType) { final Cursor cursor; if (queryType == QUERY_TYPE_EMAIL) { cursor = context .getContentResolver() .query( Queries.EMAIL.getContentUri(), Queries.EMAIL.getProjection(), Queries.EMAIL.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {String.valueOf(contactId)}, null); } else { cursor = context .getContentResolver() .query( Queries.PHONE.getContentUri(), Queries.PHONE.getProjection(), Queries.PHONE.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {String.valueOf(contactId)}, null); } return removeDuplicateDestinations(cursor); }
public static void seperate(Context c, long rawContactID) { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); Cursor cursor = c.getContentResolver() .query( RawContacts.CONTENT_URI, new String[] {RawContacts.CONTACT_ID}, RawContacts._ID + " = '" + rawContactID + "'", null, null); if (cursor.moveToFirst()) { long contactID = cursor.getLong(cursor.getColumnIndex(RawContacts.CONTACT_ID)); Set<Long> ids = getRawContacts(c, contactID, rawContactID); for (long id : ids) { ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI); builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, rawContactID); builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, id); builder.withValue( ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_SEPARATE); operationList.add(builder.build()); } if (operationList.size() > 0) try { c.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList); } catch (RemoteException e) { Log.e("Error", e.getLocalizedMessage()); } catch (OperationApplicationException e) { Log.e("Error", e.getLocalizedMessage()); } } cursor.close(); }
@Override public void onSnap(EdgeGesturePosition position) { if (position == mPosition) { return; } doHapticTriggerFeedback(); if (DEBUG) { Slog.d(TAG, "onSnap from " + position.name()); } int triggerSlots = Settings.System.getIntForUser( mContext.getContentResolver(), Settings.System.PIE_GRAVITY, EdgeGesturePosition.LEFT.FLAG, UserHandle.USER_CURRENT); triggerSlots = triggerSlots & ~mPosition.FLAG | position.FLAG; Settings.System.putIntForUser( mContext.getContentResolver(), Settings.System.PIE_GRAVITY, triggerSlots, UserHandle.USER_CURRENT); }
/** * On GSM devices, we never use short tones. On CDMA devices, it depends upon the settings. TODO: * I don't think this has anything to do with GSM versus CDMA, should we be looking only at the * setting? */ /* package */ static boolean useShortDtmfTones(Phone phone, Context context) { int toneType; int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_GSM) { return false; } else if (phoneType == Phone.PHONE_TYPE_CDMA) { if (TelephonyManager.getDefault().isMultiSimEnabled()) { toneType = android.provider.Settings.System.getInt( context.getContentResolver(), Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, MSimCallFeaturesSetting.DTMF_TONE_TYPE_NORMAL); } else { toneType = android.provider.Settings.System.getInt( context.getContentResolver(), Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL); } if (toneType == CallFeaturesSetting.DTMF_TONE_TYPE_NORMAL) { return true; } else { return false; } } else if (phoneType == Phone.PHONE_TYPE_SIP) { return false; } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } }
private Drawable prepareBackIcon(Drawable d, boolean customIcon) { int customImageColorize = Settings.System.getIntForUser( mContext.getContentResolver(), Settings.System.PIE_ICON_COLOR_MODE, 0, UserHandle.USER_CURRENT); int drawableColor = Settings.System.getIntForUser( mContext.getContentResolver(), Settings.System.PIE_ICON_COLOR, -2, UserHandle.USER_CURRENT); if (drawableColor == -2) { drawableColor = mContext.getResources().getColor(R.color.pie_foreground_color); } if (mIconResize && !customIcon) { d = resizeIcon(null, d, false); } else if (customIcon) { d = resizeIcon(null, d, true); } if ((customImageColorize != 1 || !customIcon) && customImageColorize != 3) { d = new BitmapDrawable( mContext.getResources(), ImageHelper.drawableToBitmap(ImageHelper.getColoredDrawable(d, drawableColor))); } return d; }
public MessageConverter( Context context, Preferences preferences, String userEmail, PersonLookup personLookup) { mContext = context; mMarkAsRead = preferences.getMarkAsRead(); mPersonLookup = personLookup; mMarkAsReadOnRestore = preferences.getMarkAsReadOnRestore(); String referenceUid = preferences.getReferenceUid(); if (referenceUid == null) { referenceUid = generateReferenceValue(); preferences.setReferenceUid(referenceUid); } final ContactGroup backupContactGroup = preferences.getBackupContactGroup(); ContactGroupIds allowedIds = ContactAccessor.Get.instance() .getGroupContactIds(context.getContentResolver(), backupContactGroup); if (LOCAL_LOGV) Log.v(TAG, "whitelisted ids for backup: " + allowedIds); mMessageGenerator = new MessageGenerator( mContext, new Address(userEmail), AddressStyle.getEmailAddressStyle(preferences), new HeaderGenerator(referenceUid, preferences.getVersion(true)), mPersonLookup, preferences.getMailSubjectPrefix(), allowedIds, new MmsSupport(mContext.getContentResolver(), mPersonLookup)); }
/** * Gets a drawable by URI, without using the cache. * * @return A drawable, or {@code null} if the drawable could not be loaded. */ private Drawable getDrawable(Uri uri) { try { String scheme = uri.getScheme(); if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) { // Load drawables through Resources, to get the source density information OpenResourceIdResult r = mProviderContext.getContentResolver().getResourceId(uri); try { return r.r.getDrawable(r.id); } catch (Resources.NotFoundException ex) { throw new FileNotFoundException("Resource does not exist: " + uri); } } else { // Let the ContentResolver handle content and file URIs. InputStream stream = mProviderContext.getContentResolver().openInputStream(uri); if (stream == null) { throw new FileNotFoundException("Failed to open " + uri); } try { return Drawable.createFromStream(stream, null); } finally { try { stream.close(); } catch (IOException ex) { Log.e(LOG_TAG, "Error closing icon stream for " + uri, ex); } } } } catch (FileNotFoundException fnfe) { Log.w(LOG_TAG, "Icon not found: " + uri + ", " + fnfe.getMessage()); return null; } }
/** 创建歌单 */ private static PlayList makePlaylist(final Context context, final String playlistName) { String trimmedName = playlistName.trim(); // 添加歌单到MediaStore ContentValues mInserts = new ContentValues(); mInserts.put(MediaStore.Audio.Playlists.NAME, trimmedName); mInserts.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis()); mInserts.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis()); Uri newPlaylistUri = context .getContentResolver() .insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mInserts); // 更新存储的歌单 setPlayListLib(scanPlayList(context)); // 获取新歌单ID Cursor cursor = context .getContentResolver() .query(newPlaylistUri, new String[] {MediaStore.Audio.Playlists._ID}, null, null, null); cursor.moveToFirst(); final PlayList playlist = new PlayList( cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)), playlistName); cursor.close(); return playlist; }
public static void addEmail(Context c, long rawContactId, String email) { DeviceUtil.log(c, "adding email", email); String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId + "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'"; Cursor cursor = c.getContentResolver() .query( ContactsContract.Data.CONTENT_URI, new String[] {RawContacts.CONTACT_ID}, where, null, null); if (cursor.getCount() == 0) { ContentValues contentValues = new ContentValues(); // op.put(ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID, ); contentValues.put( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId); contentValues.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email); c.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues); } cursor.close(); }
/** 向歌单添加音乐 */ public static void addSongToPlaylist( final Context context, final PlayList playlist, final Song song) { Cursor cur = context .getContentResolver() .query( MediaStore.Audio.Playlists.Members.getContentUri( "external", playlist.getmPlayListId()), null, null, null, MediaStore.Audio.Playlists.Members.TRACK + " ASC"); long count = 0; if (cur.moveToLast()) { count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK)); } cur.close(); ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1); values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, song.getmSongId()); Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.getmPlayListId()); ContentResolver resolver = context.getContentResolver(); resolver.insert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); }
@Override public Bitmap getBitmapLogo(Context context) { Bitmap thumbnailBitmap = null; if (android.os.Build.VERSION.SDK_INT >= 5) { Cursor cursor = context .getContentResolver() .query( android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, android.provider.MediaStore.Video.Media.DATA + " = '" + file.getAbsolutePath() + "'", null, null); if (cursor != null && cursor.moveToFirst()) { long id = cursor.getLong(cursor.getColumnIndex(android.provider.MediaStore.Video.Media._ID)); cursor.close(); Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail( context.getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null); thumbnailBitmap = bitmap; } else { thumbnailBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_video); } } else { thumbnailBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_video); } return thumbnailBitmap; }
// 根据号码获得联系人头像 public Bitmap getPeopleImage(String x_number) { // 获得Uri Uri uriNumber2Contacts = Uri.parse("content://com.android.contacts/" + "data/phones/filter/" + x_number); // 查询Uri,返回数据集 Cursor cursorCantacts = mContext.getContentResolver().query(uriNumber2Contacts, null, null, null, null); // 如果该联系人存在 if (cursorCantacts.getCount() > 0) { // 移动到第一条数据 cursorCantacts.moveToFirst(); // 获得该联系人的contact_id Long contactID = cursorCantacts.getLong(cursorCantacts.getColumnIndex("contact_id")); cursorCantacts.close(); // 获得contact_id的Uri Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID); // 打开头像图片的InputStream InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(), uri); // 从InputStream获得bitmap return BitmapFactory.decodeStream(input); } cursorCantacts.close(); return null; }
public static void updateContentProvider(List<Car> cars) { Context context = CarsGuideApplication.getAppContext(); if (cars != null) { for (Car car : cars) { ContentValues carsValues = new ContentValues(); carsValues.put(CarContract.ID, car.getId()); carsValues.put(CarContract.CAR_TITLE, car.getTitle()); carsValues.put(CarContract.CAR_IMAGE_URL, car.getMakeUrl()); carsValues.put(CarContract.CAR_URL, car.getUrl()); Cursor carCursor = context .getContentResolver() .query( ContentUris.withAppendedId(CarContract.CONTENT_URI, car.getId()), null, null, null, null); if (carCursor.moveToFirst()) { long id = carCursor.getLong(carCursor.getColumnIndexOrThrow(CarContract.ID)); context .getContentResolver() .update( ContentUris.withAppendedId(CarContract.CONTENT_URI, id), carsValues, null, null); } else { carsValues.put(CarContract.IS_FAVORITE, 0); context.getContentResolver().insert(CarContract.CONTENT_URI, carsValues); } carCursor.close(); } } }
private static String getAlarmPath(Context context, Alarm alarm) { String alert = alarm.alert.toString(); Uri alertUri = null; if (alert.contains("alarm_alert")) { String value = Settings.System.getString(context.getContentResolver(), "alarm_alert"); alertUri = Uri.parse(value); } else { alertUri = alarm.alert; } String[] project = {"_data"}; String path = ""; Cursor cursor = context.getContentResolver().query(alertUri, project, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { path = cursor.getString(0); Log.v("path" + path); } } catch (Exception ex) { } finally { if (cursor != null) { cursor.close(); cursor = null; } } return path; }
private void insertItem(WaitItem waitItem) { ContentValues values = new ContentValues(); values.put(GoalDatabase.WaitItemEntry.COL_TEXT, waitItem.getName()); values.put(GoalDatabase.WaitItemEntry.COL_GOAL_ID, waitItem.getGoalId()); values.put(GoalDatabase.WaitItemEntry.COL_RESPONSIBLE, waitItem.getResponsible()); Calendar dueDate = waitItem.getDueDate(); if (dueDate != null) { values.put(GoalDatabase.WaitItemEntry.COL_DUE_YEAR, dueDate.get(Calendar.YEAR)); values.put(GoalDatabase.WaitItemEntry.COL_DUE_MONTH, dueDate.get(Calendar.MONTH)); values.put(GoalDatabase.WaitItemEntry.COL_DUE_DAY, dueDate.get(Calendar.DAY_OF_MONTH)); } Calendar requestDate = waitItem.getRequestDate(); if (requestDate != null) { values.put(GoalDatabase.WaitItemEntry.COL_REQUEST_YEAR, requestDate.get(Calendar.YEAR)); values.put(GoalDatabase.WaitItemEntry.COL_REQUEST_MONTH, requestDate.get(Calendar.MONTH)); values.put( GoalDatabase.WaitItemEntry.COL_REQUEST_DAY, requestDate.get(Calendar.DAY_OF_MONTH)); } if (waitItem.getId() == 0) { mContext.getContentResolver().insert(WaitItemProvider.CONTENT_URI, values); } else { String selection = GoalDatabase.WaitItemEntry._ID + "=?"; String[] args = new String[] {Integer.valueOf(waitItem.getId()).toString()}; mContext.getContentResolver().update(WaitItemProvider.CONTENT_URI, values, selection, args); } }
public static Bitmap scaleImage(Context context, Uri uri) throws IOException { Bitmap selectedBitmap = null; try { // BitmapFactory options to downsize the image BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; o.inSampleSize = 6; // factor of downsizing the image InputStream inputStream = context.getContentResolver().openInputStream(uri); // Bitmap selectedBitmap = null; BitmapFactory.decodeStream(inputStream, null, o); inputStream.close(); // The new size we want to scale to final int REQUIRED_SIZE = 30; // Find the correct scale value. It should be the power of 2. int scale = 1; while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) { scale *= 2; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; inputStream = context.getContentResolver().openInputStream(uri); selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2); inputStream.close(); } catch (Exception e) { Log.e("", e.getMessage()); } return selectedBitmap; }
// ------------------------------------------------------ get All phone #s // numbers public ArrayList<String> getAllNumbers() { Uri uri = ContactsContract.Data.CONTENT_URI; Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); ArrayList<String> tempNumbers = null; while (cursor.moveToNext()) { String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (Boolean.parseBoolean(hasPhone)) { // You know have the number so now query it like this Cursor phones = context .getContentResolver() .query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null); while (phones.moveToNext()) { String phoneNumber = phones.getString( phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); tempNumbers.add(phoneNumber); } phones.close(); } } return tempNumbers; }
public static void PublishUnreadCount(Context context) { try { // Check if TeslaUnread is installed before doing some expensive database query ContentValues cv = new ContentValues(); cv.put("tag", "de.luhmer.owncloudnewsreader/de.luhmer.owncloudnewsreader"); cv.put("count", 0); context .getContentResolver() .insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv); // If we get here.. TeslaUnread is installed DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(context); int count = Integer.parseInt( dbConn.getUnreadItemsCountForSpecificFolder( SubscriptionExpandableListAdapter.SPECIAL_FOLDERS.ALL_UNREAD_ITEMS)); cv.put("count", count); context .getContentResolver() .insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv); } catch (IllegalArgumentException ex) { /* Fine, TeslaUnread is not installed. */ } catch (Exception ex) { /* Some other error, possibly because the format of the ContentValues are incorrect. Log but do not crash over this. */ ex.printStackTrace(); } }
public void run() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); final boolean isNoReleasedEpisodes = DisplaySettings.isNoReleasedEpisodes(mContext); final boolean isNoSpecials = DisplaySettings.isHidingSpecials(mContext); if (mShowTvdbId > 0) { // update single show DBUtils.updateLatestEpisode( mContext, mShowTvdbId, isNoReleasedEpisodes, isNoSpecials, prefs); } else { // update all shows final Cursor shows = mContext .getContentResolver() .query(Shows.CONTENT_URI, new String[] {Shows._ID}, null, null, null); if (shows != null) { while (shows.moveToNext()) { int showTvdbId = shows.getInt(0); DBUtils.updateLatestEpisode( mContext, showTvdbId, isNoReleasedEpisodes, isNoSpecials, prefs); } shows.close(); } } // Show adapter gets notified by ContentProvider // Lists adapter needs to be notified manually mContext.getContentResolver().notifyChange(ListItems.CONTENT_WITH_DETAILS_URI, null); }
private void deletePrivacyCallogs() { int sum = PrivacyContactsActivity.sPrivacyContactsListItems.size(); for (int i = 0; i < sum; i++) { PrivacyContactDataItem item = PrivacyContactsActivity.sPrivacyContactsListItems.get(i); PhoneType pt = ConvertUtils.getPhonetype(item.getPhoneNumber()); Cursor localCursor = context .getContentResolver() .query( CALLOG_URI, CALLOG_PROJECTION, "number LIKE '%" + pt.getPhoneNo() + "%'", null, null); if (localCursor != null && localCursor.getCount() > 0) { while (localCursor.moveToNext()) { int isNew = localCursor.getInt(localCursor.getColumnIndex(CallLog.Calls.NEW)); int type = localCursor.getInt(localCursor.getColumnIndex(CallLog.Calls.TYPE)); System.out.println("isNew :" + isNew); if (isNew == 1 || type == CallLog.Calls.MISSED_TYPE) { updateNotification(); } } context .getContentResolver() .delete(CALLOG_URI, "number LIKE '%" + pt.getPhoneNo() + "%'", null); } } }
public static Uri getImageContentUri(Context context, File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context .getContentResolver() .query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[] {filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); cursor.close(); return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); return context .getContentResolver() .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } }
public void setAsCurrent() { if (mUri == null) { return; } Cursor cur = mContext.getContentResolver().query(mUri, null, null, null, null); cur.moveToFirst(); int index = cur.getColumnIndex("_id"); String apnId = cur.getString(index); cur.close(); ContentValues values = new ContentValues(); values.put("apn_id", apnId); if (mSlot == -1) { mContext .getContentResolver() .update(Uri.parse("content://telephony/carriers/preferapn"), values, null, null); } else { int simNo = mSlot + 1; mContext .getContentResolver() .update( Uri.parse("content://telephony/carriers_sim" + simNo + "/preferapn"), values, null, null); } }
public static String deleteThemeDBByProductID(Context context, String productID) { String where = ThemeColumns.PRODUCT_ID + " = '" + productID + "'"; String assetPath; String name; String sceneName; Cursor cursor = context.getContentResolver().query(ThemeColumns.CONTENT_URI, null, where, null, null); if (cursor != null && cursor.moveToFirst()) { assetPath = cursor.getString(cursor.getColumnIndexOrThrow(ThemeColumns.FILE_PATH)); name = cursor.getString(cursor.getColumnIndexOrThrow(ThemeColumns.NAME)); sceneName = cursor.getString(cursor.getColumnIndexOrThrow(ThemeColumns.SCENE_NAME)); } else { if (cursor != null) { cursor.close(); } return null; } if (cursor != null) { cursor.close(); } context.getContentResolver().delete(ThemeColumns.CONTENT_URI, where, null); if (!"home8".equals(sceneName)) { where = ObjectInfoColumns.SCENE_NAME + " = '" + sceneName + "'"; context.getContentResolver().delete(ObjectInfoColumns.CONTENT_URI, where, null); } // 在老版本中资源包和wallpaper存在一个路径,假如是老版本上来的不删除这个文件夹 if (!name.equals(new File(assetPath).getName())) deleteFile(assetPath); return name; }