1.通话记录过滤
通常在显示通话记录的时候,只需要显示每个人通话记录的最后一次,那么就要过滤掉每个人多次通话记录的其它记录,一想到这个,自然就想到sql group by语句,但是通过Android提供的内容提供者getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder)去查询,不能在其中加入group by语句,通过query()方法提供的参数,最多也只能从selection去添加查询条件,那么可以通过最后一次通话的_id进行条件查询,先获得电话号码记录每个人最后一次通话记录的_id,然后组拼selection语句,下面为简单实现:
public Cursor getCursor(Context context) { Log.d(TAG, "AllMoodFragment-->getCursor()"); ContentResolver cr = context.getContentResolver(); Cursor allCursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] { CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.DATE }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER); Map<String, Integer> numberMap = new HashMap<String, Integer>(); if (allCursor != null && allCursor.getCount() > 0) { while (allCursor.moveToNext()) { String number = allCursor.getString(1); if (!numberMap.containsKey(number)) { numberMap.put(allCursor.getString(1), allCursor.getInt(0)); } } } if (allCursor != null) { allCursor.close(); allCursor = null; } StringBuilder sb = new StringBuilder(); int length = numberMap.size(); Integer[] _ids = numberMap.values().toArray(new Integer[length]); for (int i = 0; i < length; i++) { sb.append(CallLog.Calls._ID + "=" + _ids[i]); sb.append(" or "); } if (sb.length() >= 4) { sb.delete(sb.length() - 4, sb.length()); } Cursor filterCursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] { CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.DURATION, CallLog.Calls.TYPE, CallLog.Calls.CACHED_NAME }, sb.toString(), null, CallLog.Calls.DEFAULT_SORT_ORDER); return filterCursor; }
2.通话记录监听
Android提供了ContentObserver类来进行监听数据的变化,原理为设计模式中的观察着模式,实现很简单:
mContext.getContentResolver().registerContentObserver( CallLog.Calls.CONTENT_URI, true, new ContentObserver(mHandler) { @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); //当通话记录改变时,执行该方法 } });