ContentProvider(内容提供者)

ContentProvider(内容提供者)_第1张图片

其实很多时候我们用到ContentProvider并不是自己暴露自己的数据,更多的时候通过 ContentResolver来读取其他应用的信息,最常用的莫过于读取系统APP,信息,联系人, 多媒体信息等!

1)简单的读取收件箱信息:

private void getMsgs(){  
      Uri uri = Uri.parse("content://sms/"); 
      ContentResolver resolver = getContentResolver();

     //获取的是哪些列的信息 
    Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null); 
    while(cursor.moveToNext()) {
          String address = cursor.getString(0); 
          String date = cursor.getString(1); 
          String type = cursor.getString(2);
          String body = cursor.getString(3);
          System.out.println("地址:" + address);
         System.out.println("时间:" + date);
          System.out.println("类型:" + type);
          System.out.println("内容:" + body); 
          System.out.println("======================"); 
    } 
   cursor.close();
}

别忘了,往AndroidManifest.xml加入读取收件箱的权限:


2)简单的往收件箱里插入一条信息

private void insertMsg() { 
      ContentResolver resolver = getContentResolver();
      Uri uri = Uri.parse("content://sms/");
      ContentValues conValues = new ContentValues();
      conValues.put("address", "123456789"); 
      conValues.put("type", 1);
      conValues.put("date", System.currentTimeMillis());
      conValues.put("body", "no zuo no die why you try!"); 
      resolver.insert(uri, conValues);
      Log.e("HeHe", "短信插入完毕~");
}

上述代码在4.4以下都可以实现写入短信的功能,而5.0上就无法写入,原因是: 从5.0开始,默认短信应用外的软件不能以写入短信数据库的形式发短信!

3)简单的读取手机联系人

private void getContacts(){ 

    //①查询raw_contacts表获得联系人的
    id ContentResolver resolver = getContentResolver(); 
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 

    //查询联系人数据 
    cursor = resolver.query(uri, null, null, null, null); 
    while(cursor.moveToNext()) { 
    //获取联系人姓名,手机号码 
        String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        System.out.println("姓名:" + cName); 
        System.out.println("号码:" + cNum);
        System.out.println("======================");
    } 
    cursor.close();
}

别忘了加读联系人的权限:


4)查询指定电话的联系人信息

private void queryContact(String number){ 
    Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number); 
    ContentResolver resolver = getContentResolver(); 
    Cursor cursor = resolver.query(uri, new String[]{"display_name"}, null, null, null);
    if (cursor.moveToFirst()) { 
        String name = cursor.getString(0); 
        System.out.println(number + "对应的联系人名称:" + name); 
    } 
    cursor.close();
}

5)添加一个新的联系人

ContentProvider(内容提供者)_第2张图片

别忘了权限:


你可能感兴趣的:(ContentProvider(内容提供者))