CondomCore(final Context base, final CondomOptions options, final String tag) { mBase = base; DEBUG = (base.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; mExcludeBackgroundReceivers = options.mExcludeBackgroundReceivers; mExcludeBackgroundServices = SDK_INT < O && options.mExcludeBackgroundServices; mOutboundJudge = options.mOutboundJudge; mDryRun = options.mDryRun; mPackageManager = new Lazy<PackageManager>() { @Override protected PackageManager create() { return new CondomPackageManager(CondomCore.this, base.getPackageManager(), tag); }}; mContentResolver = new Lazy<ContentResolver>() { @Override protected ContentResolver create() { return new CondomContentResolver(CondomCore.this, base, base.getContentResolver()); }}; final List<CondomKit> kits = options.mKits == null ? null : new ArrayList<>(options.mKits); if (kits != null && ! kits.isEmpty()) { mKitManager = new CondomKitManager(); for (final CondomKit kit : kits) kit.onRegister(mKitManager); } else mKitManager = null; if (mDryRun) Log.w(tag, "Start dry-run mode, no outbound requests will be blocked actually, despite later stated in log."); }
@Override public void run(final Context context, final Callback callback) { ConferenceDataHandler.resetDataTimestamp(context); final Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); new AsyncTask<Context, Void, Void>() { @Override protected Void doInBackground(Context... contexts) { Account account = AccountUtils.getActiveAccount(context); if (account == null) { callback.done(false, "Cannot sync if there is no active account."); } else { new SyncHelper(contexts[0]).performSync(new SyncResult(), AccountUtils.getActiveAccount(context), bundle); } return null; } }.execute(context); }
@Override protected DocumentInfo doInBackground(Void... params) { final ContentResolver resolver = mActivity.getContentResolver(); ContentProviderClient client = null; try { final Uri childUri = DocumentsContract.renameDocument( resolver, mDoc.derivedUri, mFileName); return DocumentInfo.fromUri(resolver, childUri); } catch (Exception e) { Log.w(TAG, "Failed to rename directory", e); CrashReportingManager.logException(e); return null; } finally { ContentProviderClientCompat.releaseQuietly(client); } }
public static String getRealFilePath(final Context context, final Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { final Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { final int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { ContentResolver cr = getContext().getContentResolver(); if (fromTouch && seekBar == mStartVolumeSeekBar) { CMSettings.System.putFloat(cr, CMSettings.System.INCREASING_RING_START_VOLUME, (float) progress / 1000F); } else if (seekBar == mRampUpTimeSeekBar) { int seconds = (progress + 1) * 5; mRampUpTimeValue.setText( Formatter.formatShortElapsedTime(getContext(), seconds * 1000)); if (fromTouch) { CMSettings.System.putInt(cr, CMSettings.System.INCREASING_RING_RAMP_UP_TIME, seconds); } } }
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI, ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null, null); if (cursor.moveToFirst()) { final String data = cursor.getString(ImageThumbnailQuery._DATA); return ParcelFileDescriptor.open( new File(data), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { IoUtils.closeQuietly(cursor); } return null; }
private void deleteContactFromPhoneBook(int uid) { if (!hasContactsPermission()) { return; } synchronized (observerLock) { ignoreChanges = true; } try { ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver(); Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, currentAccount.type).build(); int value = contentResolver.delete(rawContactUri, ContactsContract.RawContacts.SYNC2 + " = " + uid, null); } catch (Exception e) { FileLog.e("tmessages", e); } synchronized (observerLock) { ignoreChanges = false; } }
/** * Decode bitmap from stream using sampling to get bitmap with the requested limit. */ static BitmapSampled decodeSampledBitmap(Context context, Uri uri, int reqWidth, int reqHeight) { try { ContentResolver resolver = context.getContentResolver(); // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options options = decodeImageForOption(resolver, uri); // Calculate inSampleSize options.inSampleSize = Math.max( calculateInSampleSizeByReqestedSize(options.outWidth, options.outHeight, reqWidth, reqHeight), calculateInSampleSizeByMaxTextureSize(options.outWidth, options.outHeight)); // Decode bitmap with inSampleSize set Bitmap bitmap = decodeImage(resolver, uri, options); return new BitmapSampled(bitmap, options.inSampleSize); } catch (Exception e) { throw new RuntimeException("Failed to load sampled bitmap: " + uri + "\r\n" + e.getMessage(), e); } }
private static void deleteFileFromMediaStore(final ContentResolver contentResolver, File file) { String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { canonicalPath = file.getAbsolutePath(); } final Uri uri = MediaStore.Files.getContentUri("external"); final int result = contentResolver.delete(uri, MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath}); if (result == 0) { final String absolutePath = file.getAbsolutePath(); if (!absolutePath.equals(canonicalPath)) { contentResolver.delete(uri, MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath}); } } }
protected AssetFileDescriptor openOrCreateVideoThumbnailCleared( long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); AssetFileDescriptor afd = openVideoThumbnailCleared(id, signal); if (afd == null) { // No thumbnail yet, so generate. This is messy, since we drop the // Bitmap on the floor, but its the least-complicated way. final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; Video.Thumbnails.getThumbnail(resolver, id, Video.Thumbnails.MINI_KIND, opts); afd = openVideoThumbnailCleared(id, signal); } return afd; }
/** * Marke all the episodes of a season as Watched * @param context * @param season */ static public void markAsRead(final Context context, final Season season) { final ContentResolver cr = context.getContentResolver(); Log.d(TAG, "markAsRead " + season.getName()+" S"+season.getSeasonNumber()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final boolean traktSync = Trakt.isTraktV2Enabled(context, prefs); final ContentValues values = new ContentValues(); values.put(VideoStore.Video.VideoColumns.BOOKMARK, PlayerActivity.LAST_POSITION_END); // TRAKT_DB_MARKED must not be marked here or TraktService would think it is already synchronized // But if there uis not trakt sync we want to have the flag in the UI as well, hence we write it here ourselves! if (!traktSync) { values.put(VideoStore.Video.VideoColumns.ARCHOS_TRAKT_SEEN, Trakt.TRAKT_DB_MARKED); } final String where = "_id IN (SELECT video_id FROM episode e JOIN show s ON e.show_episode=s._id WHERE s._id=? AND e.season_episode=?)"; final String[] selectionArgs = new String[]{Long.toString(season.getShowId()), Integer.toString(season.getSeasonNumber())}; cr.update(VideoStore.Video.Media.EXTERNAL_CONTENT_URI, values, where, selectionArgs); if (traktSync) { syncTrakt(context, season); } }
public static boolean compressDocument(ContentResolver resolver, Uri fromDocumentUri, ArrayList<String> fromDocumentIds) { final ContentProviderClient client = resolver.acquireUnstableContentProviderClient( fromDocumentUri.getAuthority()); try { final Bundle in = new Bundle(); in.putString(Document.COLUMN_DOCUMENT_ID, getDocumentId(fromDocumentUri)); in.putParcelable(DocumentsContract.EXTRA_URI, fromDocumentUri); in.putStringArrayList(DocumentsContract.EXTRA_DOCUMENTS_COMPRESS, fromDocumentIds); resolver.call(fromDocumentUri, METHOD_COMPRESS_DOCUMENT, null, in); return true; } catch (Exception e) { Log.w(TAG, "Failed to compress document", e); return false; } finally { ContentProviderClientCompat.releaseQuietly(client); } }
/** * save image to MediaStore. */ public void saveMediaStore(final ContentResolver cr) { BoxingExecutor.getInstance().runWorker(new Runnable() { @Override public void run() { if (cr != null && !TextUtils.isEmpty(getId())) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, getId()); values.put(MediaStore.Images.Media.MIME_TYPE, getMimeType()); values.put(MediaStore.Images.Media.DATA, getPath()); cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } } }); }
private String getFileNameFromContentProvider(ContentResolver contentResolver, Uri uri) { String displayName = DEFAULT_FILE_NAME; Cursor cursor = contentResolver.query(uri, ATTACHMENT_PROJECTION, null, null, null); if (cursor != null) { try { if (cursor.moveToNext() && !cursor.isNull(DISPLAY_NAME_INDEX)) { displayName = cursor.getString(DISPLAY_NAME_INDEX); } } finally { cursor.close(); } } return displayName; }
private static Set<Integer> getAllAvailableProtocolVersions(Context context) { ContentResolver contentResolver = context.getContentResolver(); Set<Integer> allAvailableVersions = new HashSet<Integer>(); Uri uri = Uri.parse("content://com.facebook.orca.provider.MessengerPlatformProvider/versions"); String [] projection = new String[]{ "version" }; Cursor c = contentResolver.query(uri, projection, null, null, null); if (c != null) { try { int versionColumnIndex = c.getColumnIndex("version"); while (c.moveToNext()) { int version = c.getInt(versionColumnIndex); allAvailableVersions.add(version); } } finally { c.close(); } } return allAvailableVersions; }
private void queryThumbnails(ContentResolver cr, String[] projection) { Cursor cur = null; try { cur = Images.Thumbnails.queryMiniThumbnails(cr, Images.Thumbnails.EXTERNAL_CONTENT_URI, Images.Thumbnails.MINI_KIND, projection); if (cur != null && cur.moveToFirst()) { do { String imageId = cur.getString(cur.getColumnIndex(Images.Thumbnails.IMAGE_ID)); String imagePath = cur.getString(cur.getColumnIndex(Images.Thumbnails.DATA)); mThumbnailMap.put(imageId, imagePath); } while (cur.moveToNext() && !cur.isLast()); } } finally { if (cur != null) { cur.close(); } } }
@Override public void onDeviceAdded(DialDevice dd) { Bundle bundledDevice = new Bundle(); MediaRouteDevice device = new MediaRouteDevice(dd); bundledDevice.putParcelable(MediaRouteDevice.EXTRA_DEVICE,device); Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getContext().getPackageName()) .build(); MediaRouteDescriptor routeDescriptor = new MediaRouteDescriptor.Builder( dd.getUuid(), dd.getFriendlyName()) .setDescription(dd.getModelName()) .setIconUri(uri) .addControlFilters(mCategoryIntentFilterList) .setExtras(bundledDevice) .build(); mRoutes.put(dd.getUuid(),routeDescriptor); publishRoutes(); }
@Override public void onIntentCompleted(WindowAndroid window, int resultCode, ContentResolver contentResolver, Intent data) { if (resultCode != Activity.RESULT_OK) return; if (data.getExtras() == null) return; VoiceResult topResult = mAutocomplete.onVoiceResults(data.getExtras()); if (topResult == null) return; String topResultQuery = topResult.getMatch(); if (TextUtils.isEmpty(topResultQuery)) return; if (topResult.getConfidence() < VOICE_SEARCH_CONFIDENCE_NAVIGATE_THRESHOLD) { setSearchQuery(topResultQuery); return; } String url = AutocompleteController.nativeQualifyPartialURLQuery(topResultQuery); if (url == null) { url = TemplateUrlService.getInstance().getUrlForVoiceSearchQuery( topResultQuery); } loadUrl(url, PageTransition.TYPED); }
public void deleteMultipleContactsAtOnce(List<String> ids) { String select = Data.CONTACT_ID + " = ?"; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (String id : ids) { String[] args = new String[] { id }; ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build()); } ContentResolver cr = ContactsManager.getInstance().getContentResolver(); try { cr.applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { Log.e(e); } }
private static Uri getCustomSound(JSONObject gcmBundle) { int soundId; String sound = gcmBundle.optString("sound", ""); if (!TextUtils.isEmpty(sound) && sound.contains(".")) { String[] str = sound.split("."); sound = str.length < 1 ? "vitrinova" : str[0]; } if (isValidResourceName(sound)) { soundId = contextResources.getIdentifier(sound, "raw", packageName); if (soundId != 0) { return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/" + soundId); } } soundId = contextResources.getIdentifier("vitrinova", "raw", packageName); if (soundId != 0) { return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/" + soundId); } return null; }
/** * Return thumbnail representing the document at the given URI. Callers are * responsible for their own in-memory caching. * * @param documentUri document to return thumbnail for, which must have * {@link Document#FLAG_SUPPORTS_THUMBNAIL} set. * @param size optimal thumbnail size desired. A provider may return a * thumbnail of a different size, but never more than double the * requested size. * @param signal signal used to indicate if caller is no longer interested * in the thumbnail. * @return decoded thumbnail, or {@code null} if problem was encountered. * @see DocumentsProvider#openDocumentThumbnail(String, Point, * CancellationSignal) */ public static Bitmap getDocumentThumbnail( ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) { final ContentProviderClient client = ContentProviderClientCompat.acquireUnstableContentProviderClient(resolver, documentUri.getAuthority()); try { if(UsbStorageProvider.AUTHORITY.equals(documentUri.getAuthority())) { return ImageUtils.getThumbnail(resolver, documentUri, size.x, size.y); } return getDocumentThumbnails(client, documentUri, size, signal); } catch (Exception e) { if (!(e instanceof OperationCanceledException)) { Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e); } return null; } finally { ContentProviderClientCompat.releaseQuietly(client); } }
private final void processFile (String file, ContentResolver cr) { String[] selectionArgs = new String[] { file }; long fileId = -1; int scraperId = -1; Cursor c = cr.query(Video.Media.getContentUriForPath(file), PROJECTION, SELECTION, selectionArgs, null); if (c != null) { if (c.moveToFirst()) { fileId = c.getLong(0); scraperId = c.getInt(1); } c.close(); } ScrapeDetailResult result = null; if (fileId > 0) { if (mForceUpdate || scraperId == 0) result = mHost.getDefaultContentAutoDetails(file); } if (result != null && result.isOkay()) { result.tag.save(mContext_, fileId); } }
public static String getUrlByIntent(Context mContext, Intent mdata) { Uri uri = mdata.getData(); String scheme = uri.getScheme(); String data = ""; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = mContext.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }
@Test public void load_withApplicationIconResourceIdUri_asDrawable_withTransformation_nonNullDrawable() throws NameNotFoundException, ExecutionException, InterruptedException { for (String packageName : getInstalledPackages()) { int iconResourceId = getResourceId(packageName); Uri uri = new Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(packageName) .path(String.valueOf(iconResourceId)) .build(); Drawable drawable = Glide.with(context) .load(uri) .apply(centerCropTransform()) .submit() .get(); assertThat(drawable).isNotNull(); } }
/** * Get the path of a file from the Uri. * * @param contentResolver the content resolver which will query for the source file * @param srcUri The source uri * @return The Path for the file or null if doesn't exists */ @Nullable public static String getRealPathFromUri(ContentResolver contentResolver, final Uri srcUri) { String result = null; if (isLocalContentUri(srcUri)) { Cursor cursor = null; try { cursor = contentResolver.query(srcUri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (idx != -1) { result = cursor.getString(idx); } } } finally { if (cursor != null) { cursor.close(); } } } else if (isLocalFileUri(srcUri)) { result = srcUri.getPath(); } return result; }
/** * Gets the corresponding path to a file from the given URI * * @param uri The URI to find the file path from * @param contentResolver The content resolver to use to perform the query. * @return the file path as a string */ public static String getPathFromUri(@NonNull Uri uri, ContentResolver contentResolver) { String filePath = null; String scheme = uri.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { String[] filePathColumn = { MediaStore.MediaColumns.DATA }; Cursor cursor = contentResolver.query(uri, filePathColumn, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); cursor.close(); } } else { filePath = uri.getPath(); } return filePath; }
/** * To find out the extension of required object in given uri * Solution by http://stackoverflow.com/a/36514823/1171484 */ public static String getMimeType(Activity context, Uri uri) { String extension; //Check uri format to avoid null if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { //If scheme is a content extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri)); if (TextUtils.isEmpty(extension))extension=MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString()); } else { //If scheme is a File //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters. extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString()); if (TextUtils.isEmpty(extension))extension=MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri)); } if(TextUtils.isEmpty(extension)){ extension=getMimeTypeByFileName(TUriParse.getFileWithUri(uri,context).getName()); } return extension; }
/** * 根据文件Uri获取文件路径 * @param context * @param uri * @return the file path or null */ public static String getRealFilePath(final Context context, final Uri uri ) { if ( null == uri ) return null; final String scheme = uri.getScheme(); String path = null; if ( scheme == null ) path = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { path = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA ); if ( index > -1 ) { path = cursor.getString( index ); } } cursor.close(); } } return path; }
public void setReminder(ContentResolver cr, long eventID, int timeBefore) { try { ContentValues values = new ContentValues(); values.put(CalendarContract.Reminders.MINUTES, timeBefore); values.put(CalendarContract.Reminders.EVENT_ID, eventID); values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values); Cursor c = CalendarContract.Reminders.query(cr, eventID, new String[]{CalendarContract.Reminders.MINUTES}); if (c.moveToFirst()) { System.out.println("calendar" + c.getInt(c.getColumnIndex(CalendarContract.Reminders.MINUTES))); } c.close(); } catch (Exception e) { e.printStackTrace(); } }
public static Point getBitmapSize(Uri uri, Activity activity) { ContentResolver resolver = activity.getContentResolver(); Point imageSize = getBitmapBound(resolver, uri); int w = imageSize.x; int h = imageSize.y; if (PhotoMetadataUtils.shouldRotate(resolver, uri)) { w = imageSize.y; h = imageSize.x; } if (h == 0) return new Point(MAX_WIDTH, MAX_WIDTH); DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); float screenWidth = (float) metrics.widthPixels; float screenHeight = (float) metrics.heightPixels; float widthScale = screenWidth / w; float heightScale = screenHeight / h; if (widthScale > heightScale) { return new Point((int) (w * widthScale), (int) (h * heightScale)); } return new Point((int) (w * widthScale), (int) (h * heightScale)); }
/** * Helper method to schedule the sync adapter periodic execution */ public static void configurePeriodicSync(Context context, long syncInterval, long flexTime) { Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // we can enable inexact timers in our periodic sync SyncRequest request = new SyncRequest.Builder(). syncPeriodic(syncInterval, flexTime). setSyncAdapter(account, authority). setExtras(new Bundle()).build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } }
public boolean onUncompressDocuments(ArrayList<DocumentInfo> docs) { final Context context = getActivity(); final ContentResolver resolver = context.getContentResolver(); boolean hadTrouble = false; for (DocumentInfo doc : docs) { if (!doc.isArchiveSupported()) { Log.w(TAG, "Skipping " + doc); hadTrouble = true; continue; } try { hadTrouble = ! DocumentsContract.uncompressDocument(resolver, doc.derivedUri); } catch (Exception e) { Log.w(TAG, "Failed to Uncompress " + doc); CrashReportingManager.logException(e); hadTrouble = true; } } return hadTrouble; }
private boolean loadImage(Uri uri, boolean verbose) { ContentResolver resolver = getContentResolver(); InputStream stream = null; if (uri != null) { mSettings.setImageUri(uri); try { stream = resolver.openInputStream(uri); } catch (Exception ex) { // e.g. FileNotFoundException, SecurityException if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isPermissionException(ex) && needsRequestReadPermission()) { requestReadPermission(REQUEST_LOAD_IMAGE_PERMISSION); return false; } showFileNotLoadedMessage(ex, verbose); } } if (stream == null || !loadImage(stream, resolver, uri)) { setDefaultBitmap(); return false; } return true; }
private void writeContactsInDB() { kontakte = new Contacts(); ContentResolver cr = RegisterActivity.this.getContentResolver(); //Activity/Application android.content.Context Map<String, String> al_contacts = kontakte.ReadKontakte(cr); // holt kontakte aus adressbuch //Map<String, String> al_downloaded_contacts = kontakte.GetRegistredOnes(al_contacts); // holt alle telefonnummern vom server; alle nutzer kontakte.GetRegistredOnes(al_contacts, FBuser.getUid()); // holt alle telefonnummern vom server; alle nutzer // Map<String, Object> al_contacts_registred = kontakte.GetYourRegistredOnes(al_contacts, al_downloaded_contacts); // holt kontakte, welche sowohl in adressbuch als auch auf server sind databaseReference.child("users").child("telefonnummern").child(telefonnummer).setValue(FBuser.getUid()); // eigene nummer in telefonummern tabelle // databaseReference.child("users").child(FBuser.getUid()).child("contacts").setValue(al_contacts_registred); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Config.REQUEST_GET_EXTRA_FILE) { if (resultCode == RESULT_OK && data != null && data.getData() != null) { ContentResolver resolver = getContentResolver(); String fileType = resolver.getType(data.getData()); if (fileType != null) { if (fileType.startsWith("image")) { Toast.makeText(this, R.string.import_file_select_error, Toast.LENGTH_SHORT).show(); finish(); return; } } DictionaryPath = URI.getAbsolutePath(this, data.getData()); String text = IOMethod.readFile(DictionaryPath); if (text != null) { TextView preview = findViewById(R.id.textview_import_text_preview); preview.setText(text); } } else { Toast.makeText(this, R.string.import_file_select_error, Toast.LENGTH_SHORT).show(); finish(); } } }
public void getContacts() { ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() <= 0) { return; } while (cur.moveToNext()) { String id = cur.getString( cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex( ContactsContract.Contacts.DISPLAY_NAME)); if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (pCur.moveToNext()) { String phoneNo = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); contact_List.add(new Kontacts(name, phoneNo)); break; } pCur.close(); } } }
public Bitmap loadData(String key) { Bitmap bitmap = null; Uri image = Uri.withAppendedPath(DBImageTable.CONTENT_URI, key); if (DEBUG) Log.d(TAG, "loaddata " + image.toString()); String[] returnCollums = new String[] { DBImageTable.DATA, }; Cursor c = null; try { ContentResolver cr = mContext.getContentResolver(); c = cr.query(image, returnCollums, null, null, null); if (DEBUG) Log.d(TAG, "count=" + c.getCount()); if(c.getCount() < 1) { return null; } if(c .getCount() > 1) { throw new RuntimeException("shouldn't reach here, make sure the NAME collumn is unique: " + key); } c.moveToFirst(); byte[] binary = c.getBlob(c.getColumnIndex(DBImageTable.DATA)); if( binary != null ) { bitmap = BitmapUtil.decodeByteArray(binary, HttpImageManager.DECODING_MAX_PIXELS_DEFAULT); if(bitmap == null) { // something wrong with the persistent data, can't be decoded to bitmap. throw new RuntimeException("data from db can't be decoded to bitmap"); } } return bitmap; } finally{ if(c != null){ c.close(); } } }
protected boolean loadData(Context context, int maxItemCount) { if(DBG) Log.d(TAG, "loadData()"); String sortOrder = VideoStore.MediaColumns.DATE_ADDED + " DESC" + " LIMIT " + maxItemCount; ContentResolver resolver = context.getContentResolver(); mCursor = resolver.query(MEDIA_DB_CONTENT_URI, VIDEO_FILES_COLUMNS, WHERE_NOT_HIDDEN, null, sortOrder); return (mCursor !=null); }
/** * 根据MIMETYPE类型, 返回对应联系人的data1字段的数据 */ private static List<String> getData1(final ContentResolver contentResolver, String contactId, final String mimeType) { List<String> dataList = new ArrayList<>(); Cursor dataCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.DATA1}, ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='" + mimeType + "'", new String[]{String.valueOf(contactId)}, null); if (dataCursor != null) { if (dataCursor.getCount() > 0) { if (dataCursor.moveToFirst()) { do { final int columnIndex = dataCursor.getColumnIndex(ContactsContract.Data.DATA1); final int type = dataCursor.getType(columnIndex); if (type == FIELD_TYPE_STRING) { final String data = dataCursor.getString(columnIndex); if (!TextUtils.isEmpty(data)) { dataList.add(data); } } } while (dataCursor.moveToNext()); } } dataCursor.close(); } return dataList; }