美文网首页Android基础知识
Android- contacts2.db数据表批量操作

Android- contacts2.db数据表批量操作

作者: ZebraWei | 来源:发表于2017-05-19 17:30 被阅读155次

    | 数据表 | 主要功能 | 主要字段 |
    | ------------- |:-------------:|: -----:|
    |calls表 | 存储通话记录信息 | number(电话号码)、 date(通话日期)、name(通话名称)、geocoded_location(电话号码所属地) |
    | groups表 | 存储手机MAC地址信息 | title(手机的mac地址) _id(Group_ID) |
    | data表 | 存储联系人信息 | data1(联系人号码、联系人名称、Group_id)、 raw_contact_id(一个联系人ID) |
    | search_index表 | 查询联系人号码 | contact_id(其实跟data表raw_contact_id关联) tokens(联系人号码) |

    主要思路
    • 1.联系人的数据库文件的位置:/data/data/com.android.providers.contacts/databases/contacts2.db
    • 2.contacts表:保存了所有的手机测联系人,每个联系人占一行,该表保存了联系人的
      ContactID、联系次数、最后一次联系的时间、是否含有号码、是否被添加到收藏夹等信息。
    • 3.data表:保存了所有创建过的手机测联系人的所有信息,每个字段占一行 ,该表
      保存了两个ID:MimeTypeID和RawContactID,从而将data表和raw_contacts表联系起来。
    • 4.在AndroidManifest.xml文件中配置如下权限:
      <uses-permission android:name="android.permission.READ_CONTACTS"
      />
      <uses-permission android:name="android.permission.WRITE_CONTACTS"
      />
    1.calls表操作

    主要对通话记录数据表清空和批量插入20条通话记录信息
    public void BatchDeleteCallLog(){
    try {
    context.getContentResolver().delete(
    android.provider.CallLog.Calls.CONTENT_URI, null, null);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    批量插入20条通话记录信息
    int size=0;
    public void BatchAddCallLog(Vector<CallLog> list) throws RemoteException,
    OperationApplicationException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentValues values = new ContentValues();

        Log.i(TAG, "name" + list.get(0).getName() + "number"
                + list.get(0).getNum());
        Log.i(TAG, "type" + String.valueOf(list.get(0).getRecordType())
                + "date" + String.valueOf(list.get(0).getTime()) + "duration"
                + String.valueOf(list.get(0).getDuration()));
        // for (CallLog calllog : list) {
        if(list.size()>20){
            size=20;
        }else{
            size=list.size();
        }
        for (int i = 0; i < size; i++) {
            int type = list.get(i).getRecordType();
            if (type == 3 || type == 1) {
                type = 3;
            } else if (type == 2) {
                type = 1;
            } else if (type == 4) {
                type = 2;
            }
            values.clear();
            values.put(android.provider.CallLog.Calls.CACHED_NAME, list.get(i).
           getName());
            values.put(android.provider.CallLog.Calls.NUMBER, list.get(i)
                    .getNum());
            values.put(android.provider.CallLog.Calls.TYPE,
                    String.valueOf(type));
            values.put(android.provider.CallLog.Calls.DATE,
                    String.valueOf(list.get(i).getTime()));
            values.put(android.provider.CallLog.Calls.DURATION,
                    String.valueOf(list.get(i).getDuration()));
            values.put(android.provider.CallLog.Calls.NEW, "0");
    
            ops.add(ContentProviderOperation
                    .newInsert(android.provider.CallLog.CONTENT_URI)
                    .withValues(values).withYieldAllowed(true).build());
        }
        // }
        if (ops != null) {
            // 真正添加
            ContentProviderResult[] results = context.getContentResolver()
                    .applyBatch(android.provider.CallLog.AUTHORITY, ops);
            Log.i(TAG, "insert success");
    
        }
      }
    
    2groups表操作

    主要对Groups表查询个数、查询存储的mac是否存在、插入mac地址、根据mac地址找到Group_id、根据mac地址删除对应信息、清空groups表。
    Groups表查询个数
    public int queryMacCountFromSystem(final Context context) {
    Cursor cursor = context.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, null, null, null, null);
    Log.i(TAG, "cursor = "+cursor);
    if(cursor == null) {
    return 0;
    } else {
    return cursor.getCount();
    }
    }
    查询存储的mac是否存在
    public boolean queryMacFromSystem(final Context context, String deviceId) {
    String where = ContactsContract.Groups.TITLE + " = ? ";
    String[] param = new String[] { deviceId + "" };
    Cursor cursor = context.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, null, where, param, null);
    if(cursor == null) {
    return false;
    } else {
    if(cursor.getCount()>0) {
    return true;
    }
    }
    return false;
    }
    插入mac地址
    public boolean insertMacToSystem(Vector<Contacts> contactsList, String deviceId) {
    if ((contactsList == null) || (contactsList.size() == 0) || !isDBEnable()) {
    return false;
    }
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    L.i(TAG, "insert mac message !");
    ops.add(ContentProviderOperation
    .newInsert(RawContacts.CONTENT_URI)
    .withValue(RawContacts.ACCOUNT_TYPE, null)
    .withValue(RawContacts.ACCOUNT_NAME, null)
    .withValue(RawContacts.AGGREGATION_MODE,
    RawContacts.AGGREGATION_MODE_DISABLED)
    .withYieldAllowed(true).build());
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Groups.CONTENT_URI)
    .withValue(Groups._ID,null)
    .withValue(Groups.TITLE, deviceId)
    .withYieldAllowed(true).build());
    if ((ops != null) && (ops.size() > 0)) {
    try {
    context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    Log.i(TAG, "insertContactsToSystem Mac OK!");
    return true;
    } catch (Exception e) {
    e.printStackTrace();
    return false;
    }

        }
         return false;
      }
    

    根据mac地址找到Group_id
    public int queryIndexGroupID(String groupName) {
    String where = Groups.TITLE + " = ? ";
    String[] param = new String[] { groupName };
    try{
    Cursor cursor = context.getContentResolver().query(Groups.CONTENT_URI, null, where, param, null);
    if ((cursor != null) && cursor.moveToFirst()) {
    return cursor.getInt(cursor.getColumnIndex(Groups._ID));
    }
    } catch (Exception e) {
    e.printStackTrace();
    }

        return -1;
      }
    

    根据mac地址删除对应信息
    public boolean delMacFromSystem(final Context context, String deviceId) {
    String where = ContactsContract.Groups.TITLE + " = ? ";
    String[] param = new String[] { deviceId + "" };
    Cursor cursor = context.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, null, where, param, null);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(Groups._ID));
            Uri uri = Uri.parse(Groups.CONTENT_URI + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
            ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(uri, id))
                    .withYieldAllowed(true).build());
        }
        
        try {
            if ((ops != null) && (ops.size() > 0)) {
                context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        
        return false;
        
      }
    
    3.data表操作

    批量插入、批量删除、根据Group_id批量插入(其中解决批量插入时,联系人数据过大导致插入失败问题)
    批量插入
    public void batchAddContact(Context context, Vector<Contacts> list, int groupsId) {
    Log.i(TAG,"start insert DataBase, Contacts size ==" + list.size()+ "groupsId =" +groupsId);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    int rawContactInsertIndex = 0;
    int count = 0;
    int startIndex = 0;
    String numbers;
    int[] types;
    for(Contacts contacts : list) {
    rawContactInsertIndex = ops.size();
    ops.add(ContentProviderOperation
    .newInsert(RawContacts.CONTENT_URI)
    .withValue(RawContacts.ACCOUNT_TYPE, null)
    .withValue(RawContacts.ACCOUNT_NAME, null)
    .withValue(RawContacts.AGGREGATION_MODE,
    RawContacts.AGGREGATION_MODE_DISABLED)
    .withYieldAllowed(true).build());

              //添加姓名
              ops.add(ContentProviderOperation
                      .newInsert(Data.CONTENT_URI)
                      .withValueBackReference(Data.RAW_CONTACT_ID,
                          rawContactInsertIndex)
                      .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                      .withValue(StructuredName.DISPLAY_NAME, contacts.getName())
                      .withYieldAllowed(true).build());
              
              ops.add(ContentProviderOperation
                      .newInsert(Data.CONTENT_URI)
                      .withValueBackReference(Data.RAW_CONTACT_ID,
                          rawContactInsertIndex)
                      .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                      .withValue(Phone.NUMBER, contacts.getNum())
                      .withValue(Phone.TYPE, Phone.TYPE_MOBILE)
                      .withYieldAllowed(true).build());
              
              ops.add(ContentProviderOperation
                      .newInsert(Data.CONTENT_URI)
                      .withValueBackReference(Data.RAW_CONTACT_ID,
                          rawContactInsertIndex)
                      .withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE)
                      .withValue(GroupMembership.GROUP_ROW_ID,
                          String.valueOf(groupsId))
                      .withYieldAllowed(true).build());
          
          //两百条同步一次
          count++;
          Log.i(TAG, "count ="+count);
          if(count == 200) {
              if(ops !=null) {
                  //真正添加
                  try{
                      context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                      Log.e(TAG, "applyBatch contacts success >200!");
                  } catch (RemoteException e) {
                      e.printStackTrace();
                      Log.e(TAG, "applyBatch error!");
                  } catch (OperationApplicationException e) {
                      e.printStackTrace();
                      Log.e(TAG,"applyBatch error!");
                  }
                  
              }
              count = 0;
              ops.clear();
              Log.i(TAG, "add 200 size!!!!");
              }
          }
          
          if(ops != null) {
                //真正添加
                  try{
                      context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                      Log.e(TAG, "applyBatch contacts success!");
                  } catch (RemoteException e) {
                      e.printStackTrace();
                      Log.e(TAG, "applyBatch error!");
                  } catch (OperationApplicationException e) {
                      e.printStackTrace();
                      Log.e(TAG,"applyBatch error!");
                  }
                  Log.i(TAG, "add stop");
             }
          
          Log.i(TAG, "add success ok !!!!!");
     
       }  
    

    批量删除
    public boolean delContactsFromSystem(final Context context, int idd) {
    String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + " = ? ";
    String[] param = new String[] { idd + "" };
    Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, param, null);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    L.i(TAG, "cursor"+cursor);
    while (cursor.moveToNext()) {
    int id = cursor.getInt(cursor.getColumnIndex(Data.RAW_CONTACT_ID));
    L.i(TAG, "strid == "+id);
    ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, id))
    .withYieldAllowed(true).build());
    }

        try {
            if ((ops != null) && (ops.size() > 0)) {
                context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                Log.i(TAG, "delContactsFromSystem OK!");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        
        return false;
        
      }
    
    search_index表信息.png data表信息.png groups表信息 .png calls表信息.png

    相关文章

      网友评论

        本文标题:Android- contacts2.db数据表批量操作

        本文链接:https://www.haomeiwen.com/subject/pmgyxxtx.html