android.content.Context#getContentResolver ( )源码实例Demo

下面列出了android.content.Context#getContentResolver ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: FireFiles   文件: DocumentsContractApi21.java
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()]);
}
 
源代码2 项目: CumulusTV   文件: TifDatabaseIntegrationTest.java
@Before
public void insertChannels() {
    Context context = getActivity();
    ContentValues contentValues = new ContentValues();
    contentValues.put(TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID, 1);
    contentValues.put(TvContract.Channels.COLUMN_DISPLAY_NAME, "Hello");
    contentValues.put(TvContract.Channels.COLUMN_DISPLAY_NUMBER, "123");
    contentValues.put(TvContract.Channels.COLUMN_INPUT_ID,
            ActivityUtils.TV_INPUT_SERVICE.flattenToString());
    contentValues.put(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_DATA, MEDIA_URL);
    Uri databaseUri = context.getContentResolver().insert(TvContract.Channels.CONTENT_URI,
            contentValues);
    Log.d(TAG, "Inserted in Uri " + databaseUri);

    // Make sure we actually inserted something
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(TvContract.Channels.CONTENT_URI,
            null, null, null, null);
    assertNotNull(cursor);
    assertEquals(1, cursor.getCount());
    assertTrue(cursor.moveToNext());
    assertEquals(1, cursor.getLong(cursor.getColumnIndex(
            TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID)));
    cursor.close();
}
 
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()]);
}
 
源代码4 项目: libcommon   文件: MediaStoreRecyclerAdapter.java
/**
 * コンストラクタ
 * @param context
 * @param itemLayout
 * @param refreshNow true: すぐにデータ取得要求する, false: refreshを呼ぶまでデータ取得しない
 */
public MediaStoreRecyclerAdapter(@NonNull final Context context,
	@LayoutRes final int itemLayout, final boolean refreshNow) {

	super();
	if (DEBUG) Log.v(TAG, "コンストラクタ:");
	mContext = context;
	mInflater = LayoutInflater.from(context);
	mLayoutId = itemLayout;
	mCr = context.getContentResolver();
	mQueryHandler = new MyAsyncQueryHandler(mCr, this);
	mThumbnailCache = new ThumbnailCache(context);
	mNeedValidate = true;

	if (refreshNow) {
		refresh();
	}
}
 
/**
 * Grant the read permission to a list of {@link Uri} sent through a {@link Intent}.
 * @param intent The sending Intent which holds a list of Uri.
 * @param uris A list of Uri generated by generateUri(Context, Bitmap, String, int,
 *             List<String>).
 * @param context The context requests to grant the permission.
 */
public static void grantReadPermission(Intent intent, List<Uri> uris, Context context) {
    if (uris == null || uris.size() == 0) return;
    ContentResolver resolver = context.getContentResolver();
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    ClipData clipData = ClipData.newUri(resolver, CLIP_DATA_LABEL, uris.get(0));
    for (int i = 1; i < uris.size(); i++) {
        clipData.addItem(new ClipData.Item(uris.get(i)));
    }
    intent.setClipData(clipData);
}
 
源代码6 项目: tinkerpatch-sdk   文件: Debugger.java
private Debugger(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cu;
    try {
        cu = cr.query(CONTENT_URI, columns, null, null, null);
    } catch (Exception e) {
        TinkerLog.e(TAG, "Get contentProvider error", e);
        cu = null;
    }

    if (cu == null || cu.getCount() <= 0) {
        TinkerLog.w(TAG, "debugger not attached cu == null");
        if (cu != null) {
            cu.close();
        }
        return;
    }

    TinkerLog.i(TAG, "debugger attached");

    final int keyIdx = cu.getColumnIndex("key");
    final int typeIdx = cu.getColumnIndex("type");
    final int valueIdx = cu.getColumnIndex("value");

    while (cu.moveToNext()) {
        final Object obj = Resolver.resolveObj(cu.getInt(typeIdx), cu.getString(valueIdx));
        values.put(cu.getString(keyIdx), obj);
    }
    cu.close();
}
 
源代码7 项目: MusicPlayer   文件: PlaylistsUtil.java
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        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();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
源代码8 项目: AndJie   文件: FileUtils.java
public static String getPath(Uri uri, Context context) {
	String[] proj = { MediaStore.Images.Media.DATA };
	ContentResolver cr = context.getContentResolver();
	Cursor cursor = cr.query(uri, proj, null, null, null);
	cursor.moveToFirst();
	int actual_image_column_index = cursor
			.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	return cursor.getString(actual_image_column_index);
}
 
源代码9 项目: android   文件: AppUtils.java
public static String getRecentSeason(Context context, int position) {

        final ContentResolver resolver = context.getContentResolver();
        final String[] cols = new String[]{RecentTable.COLUMN_SEASON};
        final Uri recentUri = RecentContentProvider.CONTENT_URI;
        final Cursor cursor = resolver.query(recentUri, cols, null, null, null);
        if (cursor != null && cursor.moveToPosition(position)) {
            String link = cursor.getString(cursor.getColumnIndex(RecentTable.COLUMN_SEASON));
            cursor.close();
            return link;
        }
        return null;
    }
 
源代码10 项目: ToGoZip   文件: SettingsActivity.java
@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);

    }
}
 
源代码11 项目: cim   文件: CIMCacheManager.java
public static void putString(Context context, String key, String value) {

        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("value", value);
        values.put("key", key);
        resolver.insert(Uri.parse(String.format(CONTENT_URI, context.getPackageName())), values);

    }
 
源代码12 项目: Telegram   文件: AudioCapabilitiesReceiver.java
/**
 * @param context A context for registering the receiver.
 * @param listener The listener to notify when audio capabilities change.
 */
public AudioCapabilitiesReceiver(Context context, Listener listener) {
  context = context.getApplicationContext();
  this.context = context;
  this.listener = Assertions.checkNotNull(listener);
  handler = new Handler(Util.getLooper());
  receiver = Util.SDK_INT >= 21 ? new HdmiAudioPlugBroadcastReceiver() : null;
  Uri externalSurroundSoundUri = AudioCapabilities.getExternalSurroundSoundGlobalSettingUri();
  externalSurroundSoundSettingObserver =
      externalSurroundSoundUri != null
          ? new ExternalSurroundSoundSettingObserver(
              handler, context.getContentResolver(), externalSurroundSoundUri)
          : null;
}
 
源代码13 项目: android-galaxyzoo   文件: LoginUtils.java
static void setAutomaticAccountSync(final Context context, final Account account) {
    final ContentResolver resolver = context.getContentResolver();
    if (resolver == null) {
        return;
    }

    ContentResolver.setSyncAutomatically(account, Item.AUTHORITY, true);
}
 
源代码14 项目: LB-Launcher   文件: LauncherModel.java
/**
 * Update the order of the workspace screens in the database. The array list contains
 * a list of screen ids in the order that they should appear.
 */
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
    // Log to disk
    Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
    Launcher.addDumpLog(TAG, "11683562 -   screens: " + TextUtils.join(", ", screens), true);

    final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
    final ContentResolver cr = context.getContentResolver();
    final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;

    // Remove any negative screen ids -- these aren't persisted
    Iterator<Long> iter = screensCopy.iterator();
    while (iter.hasNext()) {
        long id = iter.next();
        if (id < 0) {
            iter.remove();
        }
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // Clear the table
            ops.add(ContentProviderOperation.newDelete(uri).build());
            int count = screensCopy.size();
            for (int i = 0; i < count; i++) {
                ContentValues v = new ContentValues();
                long screenId = screensCopy.get(i);
                v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
            }

            try {
                cr.applyBatch(LauncherProvider.AUTHORITY, ops);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

            synchronized (sBgLock) {
                sBgWorkspaceScreens.clear();
                sBgWorkspaceScreens.addAll(screensCopy);
            }
        }
    };
    runOnWorkerThread(r);
}
 
源代码15 项目: RxTools-master   文件: RxDeviceTool.java
/**
 * 获取手机联系人
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_CONTACTS"/>}</p>
 *
 * @param context 上下文;
 * @return 联系人链表
 */
public static List<HashMap<String, String>> getAllContactInfo(Context context) {
    SystemClock.sleep(3000);
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    // 1.获取内容解析者
    ContentResolver resolver = context.getContentResolver();
    // 2.获取内容提供者的地址:com.android.contacts
    // raw_contacts表的地址 :raw_contacts
    // view_data表的地址 : data
    // 3.生成查询地址
    Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
    Uri date_uri = Uri.parse("content://com.android.contacts/data");
    // 4.查询操作,先查询raw_contacts,查询contact_id
    // projection : 查询的字段
    Cursor cursor = resolver.query(raw_uri, new String[]{"contact_id"},
            null, null, null);
    // 5.解析cursor
    while (cursor.moveToNext()) {
        // 6.获取查询的数据
        String contact_id = cursor.getString(0);
        // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
        // : 查询字段在cursor中索引值,一般都是用在查询字段比较多的时候
        // 判断contact_id是否为空
        if (!RxDataTool.isNullString(contact_id)) {//null   ""
            // 7.根据contact_id查询view_data表中的数据
            // selection : 查询条件
            // selectionArgs :查询条件的参数
            // sortOrder : 排序
            // 空指针: 1.null.方法 2.参数为null
            Cursor c = resolver.query(date_uri, new String[]{"data1",
                            "mimetype"}, "raw_contact_id=?",
                    new String[]{contact_id}, null);
            HashMap<String, String> map = new HashMap<String, String>();
            // 8.解析c
            while (c.moveToNext()) {
                // 9.获取数据
                String data1 = c.getString(0);
                String mimetype = c.getString(1);
                // 10.根据类型去判断获取的data1数据并保存
                if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                    // 电话
                    map.put("phone", data1);
                } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                    // 姓名
                    map.put("name", data1);
                }
            }
            // 11.添加到集合中数据
            list.add(map);
            // 12.关闭cursor
            c.close();
        }
    }
    // 12.关闭cursor
    cursor.close();
    return list;
}
 
源代码16 项目: codeexamples-android   文件: ExpandableList2.java
public QueryHandler(Context context, CursorTreeAdapter adapter) {
    super(context.getContentResolver());
    this.mAdapter = adapter;
}
 
源代码17 项目: Finder   文件: LocationHelper.java
/**
 * Constructor for LocationHelper.
 *
 * @param context The context which is used to read and write location mode.
 */
LocationHelper(Context context) {
    this.context = context;
    this.contentResolver = context.getContentResolver();
    this.preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
 
源代码18 项目: LB-Launcher   文件: LauncherModel.java
/**
 * Returns an ItemInfo array containing all the items in the LauncherModel.
 * The ItemInfo.id is not set through this function.
 */
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
    ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
    final ContentResolver cr = context.getContentResolver();
    Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
            LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
            LauncherSettings.Favorites.SCREEN,
            LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
            LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
            LauncherSettings.Favorites.PROFILE_ID }, null, null, null);

    final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
    final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
    final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
    final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
    final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
    final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
    final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
    final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
    UserManagerCompat userManager = UserManagerCompat.getInstance(context);
    try {
        while (c.moveToNext()) {
            ItemInfo item = new ItemInfo();
            item.cellX = c.getInt(cellXIndex);
            item.cellY = c.getInt(cellYIndex);
            item.spanX = Math.max(1, c.getInt(spanXIndex));
            item.spanY = Math.max(1, c.getInt(spanYIndex));
            item.container = c.getInt(containerIndex);
            item.itemType = c.getInt(itemTypeIndex);
            item.screenId = c.getInt(screenIndex);
            long serialNumber = c.getInt(profileIdIndex);
            item.user = userManager.getUserForSerialNumber(serialNumber);
            // Skip if user has been deleted.
            if (item.user != null) {
                items.add(item);
            }
        }
    } catch (Exception e) {
        items.clear();
    } finally {
        c.close();
    }

    return items;
}
 
源代码19 项目: android_9.0.0_r45   文件: MediaStore.java
/**
 * Gets a URI backed by a {@link DocumentsProvider} that points to the same media
 * file as the specified mediaUri. This allows apps who have permissions to access
 * media files in Storage Access Framework to perform file operations through that
 * on media files.
 * <p>
 * Note: this method doesn't grant any URI permission. Callers need to obtain
 * permission before calling this method. One way to obtain permission is through
 * a 3-step process:
 * <ol>
 *     <li>Call {@link android.os.storage.StorageManager#getStorageVolume(File)} to
 *     obtain the {@link android.os.storage.StorageVolume} of a media file;</li>
 *
 *     <li>Invoke the intent returned by
 *     {@link android.os.storage.StorageVolume#createAccessIntent(String)} to
 *     obtain the access of the volume or one of its specific subdirectories;</li>
 *
 *     <li>Check whether permission is granted and take persistent permission.</li>
 * </ol>
 * @param mediaUri the media URI which document URI is requested
 * @return the document URI
 */
public static Uri getDocumentUri(Context context, Uri mediaUri) {

    try {
        final ContentResolver resolver = context.getContentResolver();

        final String path = getFilePath(resolver, mediaUri);
        final List<UriPermission> uriPermissions = resolver.getPersistedUriPermissions();

        return getDocumentUri(resolver, path, uriPermissions);
    } catch (RemoteException e) {
        throw e.rethrowAsRuntimeException();
    }
}
 
源代码20 项目: mytracks   文件: MyTracksProviderUtils.java
/**
 * Creates an instance of {@link MyTracksProviderUtils}. Allows subclasses
 * to override for testing.
 * 
 * @param context the context
 */
protected MyTracksProviderUtils newForContext(Context context) {
  return new MyTracksProviderUtilsImpl(context.getContentResolver());
}
 
 方法所在类
 同类方法