其他分享
首页 > 其他分享> > Android通讯录管理(获取联系人、通话记录,2021Android研发必问高级面试题

Android通讯录管理(获取联系人、通话记录,2021Android研发必问高级面试题

作者:互联网

import com.suntek.contact.R;

import com.suntek.contact.model.ContactBean;

import com.suntek.contact.view.QuickAlphabeticBar;

public class ContactListAdapter extends BaseAdapter {

private LayoutInflater inflater;

private List list;

private HashMap<String, Integer> alphaIndexer; // 字母索引

private String[] sections; // 存储每个章节

private Context ctx; // 上下文

public ContactListAdapter(Context context, List list,

QuickAlphabeticBar alpha) {

this.ctx = context;

this.inflater = LayoutInflater.from(context);

this.list = list;

this.alphaIndexer = new HashMap<String, Integer>();

this.sections = new String[list.size()];

for (int i = 0; i < list.size(); i++) {

// 得到字母

String name = getAlpha(list.get(i).getSortKey());

if (!alphaIndexer.co
ntainsKey(name)) {

alphaIndexer.put(name, i);

}

}

Set sectionLetters = alphaIndexer.keySet();

ArrayList sectionList = new ArrayList(sectionLetters);

Collections.sort(sectionList); // 根据首字母进行排序

sections = new String[sectionList.size()];

sectionList.toArray(sections);

alpha.setAlphaIndexer(alphaIndexer);

}

@Override

public int getCount() {

return list.size();

}

@Override

public Object getItem(int position) {

return list.get(position);

}

@Override

public long getItemId(int position) {

return position;

}

public void remove(int position) {

list.remove(position);

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder;

if (convertView == null) {

convertView = inflater.inflate(R.layout.contact_list_item, null);

holder = new ViewHolder();

holder.quickContactBadge = (QuickContactBadge) convertView

.findViewById(R.id.qcb);

holder.alpha = (TextView) convertView.findViewById(R.id.alpha);

holder.name = (TextView) convertView.findViewById(R.id.name);

holder.number = (TextView) convertView.findViewById(R.id.number);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

ContactBean contact = list.get(position);

String name = contact.getDesplayName();

String number = contact.getPhoneNum();

holder.name.setText(name);

holder.number.setText(number);

holder.quickContactBadge.assignContactUri(Contacts.getLookupUri(

contact.getContactId(), contact.getLookUpKey()));

if (0 == contact.getPhotoId()) {

holder.quickContactBadge.setImageResource(R.drawable.touxiang);

} else {

Uri uri = ContentUris.withAppendedId(

ContactsContract.Contacts.CONTENT_URI,

contact.getContactId());

InputStream input = ContactsContract.Contacts

.openContactPhotoInputStream(ctx.getContentResolver(), uri);

Bitmap contactPhoto = BitmapFactory.decodeStream(input);

holder.quickContactBadge.setImageBitmap(contactPhoto);

}

// 当前字母

String currentStr = getAlpha(contact.getSortKey());

// 前面的字母

String previewStr = (position - 1) >= 0 ? getAlpha(list.get(

position - 1).getSortKey()) : " ";

if (!previewStr.equals(currentStr)) {

holder.alpha.setVisibility(View.VISIBLE);

holder.alpha.setText(currentStr);

} else {

holder.alpha.setVisibility(View.GONE);

}

return convertView;

}

private static class ViewHolder {

QuickContactBadge quickContactBadge;

TextView alpha;

TextView name;

TextView number;

}

/**

*/

private String getAlpha(String str) {

if (str == null) {

return “#”;

}

if (str.trim().length() == 0) {

return “#”;

}

char c = str.trim().substring(0, 1).charAt(0);

// 正则表达式匹配

Pattern pattern = Pattern.compile("1+$");

if (pattern.matcher(c + “”).matches()) {

return (c + “”).toUpperCase(); // 将小写字母转换为大写

} else {

return “#”;

}

}

}

/Contact_Demo/src/com/suntek/contact/ContactListActivity.java

package com.suntek.contact;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import android.app.Activity;

import android.content.AsyncQueryHandler;

import android.content.ContentResolver;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.provider.ContactsContract;

import android.view.View;

import android.widget.ListView;

import com.suntek.contact.adapter.ContactListAdapter;

import com.suntek.contact.model.ContactBean;

import com.suntek.contact.view.QuickAlphabeticBar;

/**

*/

public class ContactListActivity extends Activity {

private ContactListAdapter adapter;

private ListView contactList;

private List list;

private AsyncQueryHandler asyncQueryHandler; // 异步查询数据库类对象

private QuickAlphabeticBar alphabeticBar; // 快速索引条

private Map<Integer, ContactBean> contactIdMap = null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.contact_list_view);

contactList = (ListView) findViewById(R.id.contact_list);

alphabeticBar = (QuickAlphabeticBar) findViewById(R.id.fast_scroller);

// 实例化

asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());

init();

}

/**

*/

private void init() {

Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri;

// 查询的字段

String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,

ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,

ContactsContract.CommonDataKinds.Phone.DATA1, “sort_key”,

ContactsContract.CommonDataKinds.Phone.CONTACT_ID,

ContactsContract.CommonDataKinds.Phone.PHOTO_ID,

ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY };

// 按照sort_key升序查詢

asyncQueryHandler.startQuery(0, null, uri, projection, null, null,

“sort_key COLLATE LOCALIZED asc”);

}

/**

*/

private class MyAsyncQueryHandler extends AsyncQueryHandler {

public MyAsyncQueryHandler(ContentResolver cr) {

super(cr);

}

@Override

protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

if (cursor != null && cursor.getCount() > 0) {

contactIdMap = new HashMap<Integer, ContactBean>();

list = new ArrayList();

cursor.moveToFirst(); // 游标移动到第一项

for (int i = 0; i < cursor.getCount(); i++) {

cursor.moveToPosition(i);

String name = cursor.getString(1);

String number = cursor.getString(2);

String sortKey = cursor.getString(3);

int contactId = cursor.getInt(4);

Long photoId = cursor.getLong(5);

String lookUpKey = cursor.getString(6);

if (contactIdMap.containsKey(contactId)) {

// 无操作

} else {

// 创建联系人对象

ContactBean contact = new ContactBean();

contact.setDesplayName(name);

contact.setPhoneNum(number);

contact.setSortKey(sortKey);

contact.setPhotoId(photoId);

contact.setLookUpKey(lookUpKey);

list.add(contact);

contactIdMap.put(contactId, contact);

}

}

if (list.size() > 0) {

setAdapter(list);

}

}

super.onQueryComplete(token, cookie, cursor);

}

}

private void setAdapter(List list) {

adapter = new ContactListAdapter(this, list, alphabeticBar);

contactList.setAdapter(adapter);

alphabeticBar.init(ContactListActivity.this);

alphabeticBar.setListView(contactList);

alphabeticBar.setHight(alphabeticBar.getHeight());

alphabeticBar.setVisibility(View.VISIBLE);

}

}

自定义组件:

package com.suntek.contact.view;

import android.content.Context;

import android.util.AttributeSet;

import android.view.MotionEvent;

import android.widget.LinearLayout;

public class SlidingLinearLayout extends LinearLayout {

public SlidingLinearLayout(Context context, AttributeSet attrs) {

super(context, attrs);

}

@Override

public boolean onInterceptTouchEvent(MotionEvent ev) {

return super.onInterceptTouchEvent(ev);

}

}

/Contact_Demo/src/com/suntek/contact/view/QuickAlphabeticBar.java

package com.suntek.contact.view;

import java.util.HashMap;

import android.app.Activity;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Typeface;

import android.os.Handler;

import android.util.AttributeSet;

import android.view.MotionEvent;

import android.view.View;

import android.widget.ImageButton;

import android.widget.ListView;

import android.widget.TextView;

import com.suntek.contact.R;

/**

*/

public class QuickAlphabeticBar extends ImageButton {

private TextView mDialogText; // 中间显示字母的文本框

private Handler mHandler; // 处理UI的句柄

private ListView mList; // 列表

private float mHight; // 高度

// 字母列表索引

private String[] letters = new String[] { “#”, “A”, “B”, “C”, “D”, “E”,

“F”, “G”, “H”, “I”, “J”, “K”, “L”, “M”, “N”, “O”, “P”, “Q”, “R”,

“S”, “T”, “U”, “V”, “W”, “X”, “Y”, “Z” };

// 字母索引哈希表

private HashMap<String, Integer> alphaIndexer;

Paint paint = new Paint();

boolean showBkg = false;

int choose = -1;

public QuickAlphabeticBar(Context context) {

super(context);

}

public QuickAlphabeticBar(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

public QuickAlphabeticBar(Context context, AttributeSet attrs) {

super(context, attrs);

}

// 初始化

public void init(Activity ctx) {

mDialogText = (TextView) ctx.findViewById(R.id.fast_position);

mDialogText.setVisibility(View.INVISIBLE);

mHandler = new Handler();

}

// 设置需要索引的列表

public void setListView(ListView mList) {

this.mList = mList;

}

// 设置字母索引哈希表

public void setAlphaIndexer(HashMap<String, Integer> alphaIndexer) {

this.alphaIndexer = alphaIndexer;

}

// 设置字母索引条的高度

public void setHight(float mHight) {

this.mHight = mHight;

}

@Override

public boolean onTouchEvent(MotionEvent event) {

int act = event.getAction();

float y = event.getY();

final int oldChoose = choose;

// 计算手指位置,找到对应的段,让mList移动段开头的位置上

int selectIndex = (int) (y / (mHight / letters.length));

if (selectIndex > -1 && selectIndex < letters.length) { // 防止越界

String key = letters[selectIndex];

if (alphaIndexer.containsKey(key)) {

int pos = alphaIndexer.get(key);

if (mList.getHeaderViewsCount() > 0) { // 防止ListView有标题栏,本例中没有

this.mList.setSelectionFromTop(

pos + mList.getHeaderViewsCount(), 0);

} else {

this.mList.setSelectionFromTop(pos, 0);

}

mDialogText.setText(letters[selectIndex]);

}

}

switch (act) {

case MotionEvent.ACTION_DOWN:

showBkg = true;

if (oldChoose != selectIndex) {

if (selectIndex > 0 && selectIndex < letters.length) {

choose = selectIndex;

invalidate();

}

}

if (mHandler != null) {

mHandler.post(new Runnable() {

@Override

public void run() {

if (mDialogText != null

&& mDialogText.getVisibility() == View.INVISIBLE) {

mDialogText.setVisibility(VISIBLE);

}

}

});

}

break;

case MotionEvent.ACTION_MOVE:

if (oldChoose != selectIndex) {

if (selectIndex > 0 && selectIndex < letters.length) {

choose = selectIndex;

invalidate();

}

}

break;

case MotionEvent.ACTION_UP:

showBkg = false;

choose = -1;

if (mHandler != null) {

mHandler.post(new Runnable() {

@Override

public void run() {

if (mDialogText != null

&& mDialogText.getVisibility() == View.VISIBLE) {

mDialogText.setVisibility(INVISIBLE);

}

}

});

}

break;

default:

break;

}

return super.onTouchEvent(event);

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

int height = getHeight();

int width = getWidth();

int sigleHeight = height / letters.length; // 单个字母占的高度

for (int i = 0; i < letters.length; i++) {

paint.setColor(Color.WHITE);

paint.setTextSize(20);

paint.setTypeface(Typeface.DEFAULT_BOLD);
break;

case MotionEvent.ACTION_MOVE:

if (oldChoose != selectIndex) {

if (selectIndex > 0 && selectIndex < letters.length) {

choose = selectIndex;

invalidate();

}

}

break;

case MotionEvent.ACTION_UP:

showBkg = false;

choose = -1;

if (mHandler != null) {

mHandler.post(new Runnable() {

@Override

public void run() {

if (mDialogText != null

&& mDialogText.getVisibility() == View.VISIBLE) {

mDialogText.setVisibility(INVISIBLE);

}

}

});

}

break;

default:

break;

}

return super.onTouchEvent(event);

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

int height = getHeight();

int width = getWidth();

int sigleHeight = height / letters.length; // 单个字母占的高度

for (int i = 0; i < letters.length; i++) {

paint.setColor(Color.WHITE);

paint.setTextSize(20);

paint.setTypeface(Typeface.DEFAULT_BOLD);


  1. A-Za-z ↩︎

标签:面试题,int,通话记录,list,contact,通讯录,import,android,public
来源: https://blog.csdn.net/m0_66264533/article/details/122759681