Java Code Examples for android.content.ContentResolver

The following are top voted examples for showing how to use android.content.ContentResolver. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: condom   File: CondomCore.java   Source Code and License 8 votes vote down vote up
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.");
}
 
Example 2
Project: iosched-reader   File: ForceSyncNowAction.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 3
Project: AvenueNet   File: FileUtils.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 4
Project: FireFiles   File: StorageProvider.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 5
Project: Gallery-example   File: DeleteFileUtils.java   Source Code and License 7 votes vote down vote up
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});
            }
        }
    }
 
Example 6
Project: aos-Video   File: DbUtils.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 7
Project: NeiHanDuanZiTV   File: ImageMedia.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
            }
        }
    });

}
 
Example 8
Project: omnicrow-android   File: GenerateNotification.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 9
Project: simple-share-android   File: DocumentsContract.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Project: aos-MediaLib   File: Scraper.java   Source Code and License 7 votes vote down vote up
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);
    }
}
 
Example 11
Project: GitHub   File: BindingUtils.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 12
Project: GitHub   File: UriUtil.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 13
Project: GitHub   File: TImageFiles.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: GitHub   File: ImageMedia.java   Source Code and License 7 votes vote down vote up
/**
 * 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);
            }
        }
    });

}
 
Example 15
Project: Tess-TwoDemo   File: FileUtils.java   Source Code and License 7 votes vote down vote up
/**
 * 根据文件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;
}
 
Example 16
Project: easyfilemanager   File: DirectoryFragment.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 17
Project: SSTVEncoder2   File: MainActivity.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 18
Project: chapp-messenger   File: RegisterActivity.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 19
Project: aos-MediaLib   File: DBPersistence.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 20
Project: aos-Video   File: RemoteViewsFactoryRecentlyAdded.java   Source Code and License 6 votes vote down vote up
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);
  }
 
Example 21
Project: RLibrary   File: ContactsPickerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 根据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;
}
 
Example 22
Project: easyfilemanager   File: RenameFragment.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 23
Project: NovaMusicPlayer   File: MediaStoreHelper.java   Source Code and License 5 votes vote down vote up
public static ArrayList<Track> loadTrackList(ContentResolver resolver, String selection,
                                                 String[] selectionArgs, String sortOrder) {
        ArrayList<Track> list = new ArrayList<>();
        Cursor cursor = resolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.IS_MUSIC,    /* for checking if is music*/
                        MediaStore.Audio.Media._ID,         /* */
                        MediaStore.Audio.Media.TITLE,       /* for displaying in SongListFragment */
                        MediaStore.Audio.Media.DURATION,    /* for displaying in SongListFragment */
                        MediaStore.Audio.Media.DATA,        /* for playing */
                        MediaStore.Audio.Media.TRACK,       /* for displaying in AlbumFragment */
                        MediaStore.Audio.Media.ALBUM_ID,    /* for getting the album art*/
//                        MediaStore.Audio.Media.ALBUM,       /* for displaying in SongListFragment */
//                        MediaStore.Audio.Media.ARTIST       /* for displaying in SongListFragment */
                },
                selection, selectionArgs, sortOrder);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    if (cursor.getInt(0) == 1) {
                        Track track = new Track();
                        track.setId(cursor.getInt(1));
                        track.setTitle(cursor.getString(2));
                        track.setDuration(cursor.getInt(3));
                        track.setPath(cursor.getString(4));
                        track.setTrackNum(cursor.getInt(5));
                        track.setAlbumId(cursor.getInt(6));
//                        track.setAlbum(cursor.getString(7));
//                        track.setArtist(cursor.getString(8));
                        list.add(track);
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return list;
    }
 
Example 24
Project: DemoMode   File: RealDemoModeInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public GrantPermissionResult setDemoModeSetting(DemoModeSetting setting) {
  if (setting == getDemoModeSetting()) {
    return SUCCESS;
  }
  GrantPermissionResult result = grantPermission(PERMISSION_WRITE_SECURE_SETTINGS);
  if (result != SUCCESS) {
    return result;
  }
  String value;
  switch (setting) {
    case ENABLED:
      value = "1";
      break;
    case DISABLED:
      value = "0";
      break;
    case DISABLED_NEVER_SET:
      value = null;
      break;
    default:
      throw new AssertionError("No DemoModeSetting type: " + setting);
  }
  ContentResolver resolver = context.getContentResolver();
  Settings.Global.putString(resolver, SYSTEMUI_DEMO_ALLOWED, value);
  return SUCCESS;
}
 
Example 25
Project: lineagex86   File: IncreasingRingVolumePreference.java   Source Code and License 5 votes vote down vote up
@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);
        }
    }
}
 
Example 26
Project: easyfilemanager   File: DocumentsContract.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new document with given MIME type and display name.
 *
 * @param parentDocumentUri directory with
 *            {@link DocumentsContract.Document#FLAG_DIR_SUPPORTS_CREATE}
 * @param mimeType MIME type of new document
 * @param displayName name of new document
 * @return newly created document, or {@code null} if failed
 */
public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri,
                                 String mimeType, String displayName) {
    final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
            parentDocumentUri.getAuthority());
    try {
        return createDocument(client, parentDocumentUri, mimeType, displayName);
    } catch (Exception e) {
        Log.w(TAG, "Failed to create document", e);
        return null;
    } finally {
        ContentProviderClientCompat.releaseQuietly(client);
    }
}
 
Example 27
Project: react-native-sync-adapter   File: SyncAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to have the sync adapter sync immediately
 */
public static void syncImmediately(Context context, int syncInterval, int syncFlexTime) {
    Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    ContentResolver.requestSync(getSyncAccount(context, syncInterval, syncFlexTime),
            context.getString(R.string.rnsb_content_authority), bundle);
}
 
Example 28
Project: airgram   File: ContactsController.java   Source Code and License 5 votes vote down vote up
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;
    }
}
 
Example 29
Project: Cluttr   File: BitmapUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 30
Project: Hello-Music-droid   File: MusicPlayer.java   Source Code and License 5 votes vote down vote up
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + "play_order" + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    int base = 0;

    try {
        cursor = resolver.query(uri, projection, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            base = cursor.getInt(0) + 1;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    int numinserted = 0;
    for (int offSet = 0; offSet < size; offSet += 1000) {
        makeInsertItems(ids, offSet, 1000, base);
        numinserted += resolver.bulkInsert(uri, mContentValuesCache);
    }
    final String message = context.getResources().getQuantityString(
            R.plurals.NNNtrackstoplaylist, numinserted, numinserted);
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
 
Example 31
Project: FireFiles   File: StorageProvider.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: javaide   File: CrashConstants.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to generate a device identifier for telemetry and crashes,
 *
 * @param context The context to use. Usually your Activity object.
 */
private static void loadDeviceIdentifier(Context context) {
    // get device ID
    ContentResolver resolver = context.getContentResolver();
    String deviceIdentifier = Settings.Secure.getString(resolver, Settings.Secure.ANDROID_ID);
    if (deviceIdentifier != null) {
        CrashConstants.DEVICE_IDENTIFIER = tryHashStringSha256(context, deviceIdentifier);
    }
}
 
Example 33
Project: FireFiles   File: DocumentsContract.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 34
Project: CSipSimple   File: Compatibility.java   Source Code and License 5 votes vote down vote up
/**
 * Get the current wifi sleep policy
 * @param ctntResolver android content resolver
 * @return the current wifi sleep policy
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static int getWifiSleepPolicy(ContentResolver ctntResolver) {
    if(Compatibility.isCompatible(Build.VERSION_CODES.JELLY_BEAN_MR1)) {
        return Settings.Global.getInt(ctntResolver, Settings.Global.WIFI_SLEEP_POLICY, Settings.Global.WIFI_SLEEP_POLICY_DEFAULT);
    }else {
        return Settings.System.getInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
    }
}
 
Example 35
Project: FireFiles   File: StorageProvider.java   Source Code and License 5 votes vote down vote up
protected long getImageForPathCleared(String path) throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
                ImagesBucketThumbnailQuery.PROJECTION, ImageColumns.DATA + "= ? ",
                new String[] { path.replaceAll("'", "''") }, ImageColumns.DATE_MODIFIED + " DESC");
        if (cursor.moveToFirst()) {
            return cursor.getLong(ImagesBucketThumbnailQuery._ID);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    throw new FileNotFoundException("No image found for bucket");
}
 
Example 36
Project: q-mail   File: DownloadImageTask.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 37
Project: aos-MediaLib   File: LibraryUtils.java   Source Code and License 5 votes vote down vote up
public static Cursor getScraperCursorFromPath(ContentResolver resolver, String filePath) {
    StringBuilder where = new StringBuilder();
    where.append(VideoStore.Video.VideoColumns.DATA).append("= ?");
    where.append(" AND ").append(VideoStore.Video.VideoColumns.ARCHOS_MEDIA_SCRAPER_ID).append(" > '0'");
    String[] selectionArgs = new String[1];
    selectionArgs[0] = filePath;
    return resolver.query(VideoStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_COLS, where.toString(), selectionArgs, null);
}
 
Example 38
Project: Quran   File: QuranImportPresenterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testParseExternalFileNullIs() throws FileNotFoundException {
  ContentResolver resolver = mock(ContentResolver.class);
  when(resolver.openInputStream(any(Uri.class))).thenReturn(null);
  when(appContext.getContentResolver()).thenReturn(resolver);

  TestObserver<BufferedSource> observer = new TestObserver<>();
  presenter.parseExternalFile(Uri.EMPTY)
      .subscribe(observer);
  observer.awaitTerminalEvent();
  observer.assertValueCount(0);
  observer.assertNoErrors();
  observer.assertComplete();
}
 
Example 39
Project: kognitivo   File: MessengerUtils.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 40
Project: PlusGram   File: ContactsController.java   Source Code and License 5 votes vote down vote up
protected void markAsContacted(final String contactId) {
    if (contactId == null) {
        return;
    }
    Utilities.phoneBookQueue.postRunnable(new Runnable() {
        @Override
        public void run() {
            Uri uri = Uri.parse(contactId);
            ContentValues values = new ContentValues();
            values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, System.currentTimeMillis());
            ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
            cr.update(uri, values, null, null);
        }
    });
}