Android通讯录管理(获取联系人、通话记录、短信消息)(三)

Android通讯录管理(获取联系人、通话记录、短信消息)(三)



这是通讯录管理的最后一篇,前面两篇已经把获取联系人和通话记录解决了,短息消息就相对来说要稍微复杂那么一点。我们先来看看效果图:
源码下载:http://download.csdn.net/detail/wwj_748/6962865

Android通讯录管理(获取联系人、通话记录、短信消息)(三)_第1张图片Android通讯录管理(获取联系人、通话记录、短信消息)(三)_第2张图片   





首先显示短信列表,每个列表会显示发送人号码,日期还有短信的内容概要,点击列表之后进入穿查看会话的短信消息,这里为了简单起见就没有把发送消息的功能加进去了。

布局界面:
/Contact_Demo/res/layout/sms_list_view.xml



    


/Contact_Demo/res/layout/sms_list_item.xml



    

    

        

        
    

    

    



短息实体类:

/Contact_Demo/src/com/suntek/contact/model/SMSBean.java
package com.suntek.contact.model;

public class SMSBean {

	private String thread_id; // 线程id
	private String msg_count; // 消息个数
	private String msg_snippet; // 消息片段
	private String address; // 地址
	private Long date; // 日期
	private String read; // 已读

	public SMSBean(String threadId, String msgCount, String msgSnippet) {
		thread_id = threadId;
		msg_count = msgCount;
		msg_snippet = msgSnippet;
	}

	public SMSBean() {
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Long getDate() {
		return date;
	}

	public void setDate(Long date) {
		this.date = date;
	}

	public String getRead() {
		return read;
	}

	public void setRead(String read) {
		this.read = read;
	}

	public String getThread_id() {
		return thread_id;
	}

	public void setThread_id(String threadId) {
		thread_id = threadId;
	}

	public String getMsg_count() {
		return msg_count;
	}

	public void setMsg_count(String msgCount) {
		msg_count = msgCount;
	}

	public String getMsg_snippet() {
		return msg_snippet;
	}

	public void setMsg_snippet(String msgSnippet) {
		msg_snippet = msgSnippet;
	}
}

短信列表适配器:
/Contact_Demo/src/com/suntek/contact/adapter/SMSAdpter.java
package com.suntek.contact.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.suntek.contact.R;
import com.suntek.contact.model.SMSBean;

/**
 * 短信适配器
 * 
 * @author Administrator
 * 
 */
public class SMSAdpter extends BaseAdapter {
	private LayoutInflater mInflater;
	private List smsList;
	private Date date;
	private SimpleDateFormat sdf;

	public SMSAdpter(Context context) {
		mInflater = LayoutInflater.from(context);
		this.smsList = new ArrayList();
		this.date = new Date();
		this.sdf = new SimpleDateFormat("MM/dd HH:mm");
	}

	public void assignment(List smsList) {
		this.smsList = smsList;
	}

	public void add(SMSBean bean) {
		smsList.add(bean);
	}

	public void remove(int position) {
		smsList.remove(position);
	}

	@Override
	public int getCount() {
		return smsList.size();
	}

	@Override
	public Object getItem(int position) {
		return smsList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.sms_list_item, parent,
					false);
			holder = new ViewHolder();
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.count = (TextView) convertView.findViewById(R.id.count);
			holder.date = (TextView) convertView.findViewById(R.id.date);
			holder.content = (TextView) convertView.findViewById(R.id.content);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.name.setText(smsList.get(position).getAddress());
		holder.count.setText("(" + smsList.get(position).getMsg_count() + ")");

		this.date.setTime(smsList.get(position).getDate());
		holder.date.setText(this.sdf.format(date));

		holder.content.setText(smsList.get(position).getMsg_snippet());

		convertView.setTag(holder);
		return convertView;
	}

	public final class ViewHolder {
		public TextView name;
		public TextView count;
		public TextView date;
		public TextView content;
	}
}

Activity界面
/Contact_Demo/src/com/suntek/contact/SMSListActivity.java
package com.suntek.contact;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.suntek.contact.adapter.SMSAdpter;
import com.suntek.contact.model.SMSBean;
import com.suntek.contact.util.BaseIntentUtil;
import com.suntek.contact.util.RexseeSMS;

/**
 * 短信列表
 * 
 * @author Administrator
 * 
 */
public class SMSListActivity extends Activity {

	private ListView smsListView;
	private SMSAdpter smsAdpter;
	private RexseeSMS rsms;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_list_view);
		smsListView = (ListView) findViewById(R.id.sms_list);
		smsAdpter = new SMSAdpter(SMSListActivity.this);
		rsms = new RexseeSMS(SMSListActivity.this);
		List list_mmt = rsms.getThreadsNum(rsms.getThreads(0));
		// 注入短信列表数据
		smsAdpter.assignment(list_mmt);
		// 填充数据
		smsListView.setAdapter(smsAdpter);
		// 短信列表项点击事件
		smsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				Map map = new HashMap();
				SMSBean sb = (SMSBean) smsAdpter.getItem(position);
				map.put("phoneNumber", sb.getAddress());
				map.put("threadId", sb.getThread_id());
				BaseIntentUtil.intentSysDefault(SMSListActivity.this,
						MessageBoxList.class, map);
			}
		});
	}
}


查询短信的工具类:
/Contact_Demo/src/com/suntek/contact/util/RexseeSMS.java
package com.suntek.contact.util;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.suntek.contact.model.SMSBean;

public class RexseeSMS {

	public static final String CONTENT_URI_SMS = "content://sms"; // 短信
	public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox";// 收件箱
	public static final String CONTENT_URI_SMS_SENT = "content://sms/sent"; // 发送
	public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations";

	public RexseeSMS(Context mContext) {
		this.mContext = mContext;
		// TODO Auto-generated constructor stub
	}

	public static String[] SMS_COLUMNS = new String[] { "_id", // 0
			"thread_id", // 1
			"address", // 2
			"person", // 3
			"date", // 4
			"body", // 5
			"read", // 6; 0:not read 1:read; default is 0
			"type", // 7; 0:all 1:inBox 2:sent 3:draft 4:outBox 5:failed
					// 6:queued
			"service_center" // 8
	};
	public static String[] THREAD_COLUMNS = new String[] { "thread_id",
			"msg_count", "snippet" };

	private Context mContext;

	public String getContentUris() {
		String rtn = "{";
		rtn += "\"sms\":\"" + CONTENT_URI_SMS + "\"";
		rtn += ",\"inbox\":\"" + CONTENT_URI_SMS_INBOX + "\"";
		rtn += ",\"sent\":\"" + CONTENT_URI_SMS_SENT + "\"";
		rtn += ",\"conversations\":\"" + CONTENT_URI_SMS_CONVERSATIONS + "\"";
		rtn += "}";
		return rtn;
	}

	public String get(int number) {
		return getData(null, number);
	}

	public String getUnread(int number) {
		return getData("type=1 AND read=0", number);
	}

	public String getRead(int number) {
		return getData("type=1 AND read=1", number);
	}

	public String getInbox(int number) {
		return getData("type=1", number);
	}

	public String getSent(int number) {
		return getData("type=2", number);
	}

	public String getByThread(int thread) {
		return getData("thread_id=" + thread, 0);
	}

	public String getData(String selection, int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		try {
			if (number > 0) {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
						SMS_COLUMNS, selection, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return "[]";
			String rtn = "";
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				if (i > 0)
					rtn += ",";
				rtn += "{";
				rtn += "\"_id\":" + cursor.getString(0);
				rtn += ",\"thread_id\":" + cursor.getString(1);
				rtn += ",\"address\":\"" + cursor.getString(2) + "\"";
				rtn += ",\"person\":\""
						+ ((cursor.getString(3) == null) ? "" : cursor
								.getString(3)) + "\"";
				rtn += ",\"date\":" + cursor.getString(4);
				rtn += ",\"body\":\"" + cursor.getString(5) + "\"";
				rtn += ",\"read\":"
						+ ((cursor.getInt(6) == 1) ? "true" : "false");
				rtn += ",\"type\":" + cursor.getString(7);
				rtn += ",\"service_center\":" + cursor.getString(8);
				rtn += "}";
			}
			return "[" + rtn + "]";
		} catch (Exception e) {
			return "[]";
		}
	}

	public List getThreads(int number) {
		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List list = new ArrayList();
		try {
			if (number > 0) {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "thread_id desc limit "
								+ number);
			} else {
				cursor = contentResolver.query(
						Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
						THREAD_COLUMNS, null, null, "date desc");
			}
			if (cursor == null || cursor.getCount() == 0)
				return list;
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				SMSBean mmt = new SMSBean(cursor.getString(0),
						cursor.getString(1), cursor.getString(2));
				list.add(mmt);
			}
			return list;
		} catch (Exception e) {
			return list;
		}
	}

	public List getThreadsNum(List ll) {

		Cursor cursor = null;
		ContentResolver contentResolver = mContext.getContentResolver();
		List list = new ArrayList();
		// try {
		for (SMSBean mmt : ll) {
			cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
					SMS_COLUMNS, "thread_id = " + mmt.getThread_id(), null,
					null);
			if (cursor == null || cursor.getCount() == 0)
				return list;
			cursor.moveToFirst();
			mmt.setAddress(cursor.getString(2));
			mmt.setDate(cursor.getLong(4));
			mmt.setRead(cursor.getString(6));
			list.add(mmt);
		}

		return list;
		// } catch (Exception e) {
		// Log.e("getThreadsNum", "getThreadsNum-------------");
		// return list;
		// }
	}
}




上面是短信列表的实现,下面是会话消息的实现

界面布局:
/Contact_Demo/res/layout/message_list_view.xml



    


/Contact_Demo/res/layout/list_say_he_item.xml



    

        

        
    


/Contact_Demo/res/layout/list_say_me_item.xml



    

        

        
    





短信消息实体类:
/Contact_Demo/src/com/suntek/contact/model/MessageBean.java
package com.suntek.contact.model;

public class MessageBean {

	private String name; // 联系人姓名
	private String date; // 日期
	private String text; // 文本
	private int layoutID; // 布局id,区分是发送人还是接收人

	public MessageBean() {
	}

	public MessageBean(String name, String date, String text, int layoutID) {
		super();
		this.name = name;
		this.date = date;
		this.text = text;
		this.layoutID = layoutID;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getLayoutID() {
		return layoutID;
	}

	public void setLayoutID(int layoutID) {
		this.layoutID = layoutID;
	}
}

消息列表适配器:
/Contact_Demo/src/com/suntek/contact/adapter/MessageBoxListAdapter.java
package com.suntek.contact.adapter;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.ClipboardManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.suntek.contact.R;
import com.suntek.contact.model.MessageBean;

/**
 * 消息列表适配器
 * 
 * @author Administrator
 * 
 */
public class MessageBoxListAdapter extends BaseAdapter {

	private List mbList;
	private Context ctx;
	private LinearLayout layout_father;
	private LayoutInflater vi;
	private LinearLayout layout_child;
	private TextView tvDate;
	private TextView tvText;

	public MessageBoxListAdapter(Context context, List coll) {
		ctx = context;
		vi = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.mbList = coll;
	}

	public int getCount() {
		return mbList.size();
	}

	public Object getItem(int position) {
		return mbList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

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

		MessageBean mb = mbList.get(position);
		// 得到布局ID
		int itemLayout = mb.getLayoutID();
		layout_father = new LinearLayout(ctx);
		vi.inflate(itemLayout, layout_father, true);

		layout_father.setBackgroundColor(Color.TRANSPARENT);
		layout_child = (LinearLayout) layout_father
				.findViewById(R.id.layout_bj);

		tvText = (TextView) layout_father
				.findViewById(R.id.messagedetail_row_text);
		tvText.setText(mb.getText());

		tvDate = (TextView) layout_father
				.findViewById(R.id.messagedetail_row_date);
		tvDate.setText(mb.getDate());

		addListener(tvText, tvDate, layout_child, mb);

		return layout_father;
	}

	public void addListener(final TextView tvText, final TextView tvDate,
			LinearLayout layout_bj, final MessageBean mb) {

		layout_bj.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

			}
		});

		layout_bj.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				tvText.setTextColor(0xffffffff);
				showListDialog(newtan, mb);
				return true;
			}
		});

		layout_bj.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:

				case MotionEvent.ACTION_MOVE:
					tvText.setTextColor(0xffffffff);
					break;

				default:
					tvText.setTextColor(Color.BLACK);
					break;
				}
				return false;
			}
		});
	}

	private String[] newtan = new String[] { "转发", "复制文本内容", "删除", "查询信息详情" };

	private void showListDialog(final String[] arg, final MessageBean mb) {
		new AlertDialog.Builder(ctx).setTitle("信息选项")
				.setItems(arg, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {

						case 0:
							break;

						case 1:
							ClipboardManager cmb = (ClipboardManager) ctx
									.getSystemService(ctx.CLIPBOARD_SERVICE);
							cmb.setText(mb.getText());
							break;
						case 2:

							break;
						case 3:
							break;
						}
						;
					}
				}).show();
	}
}


/Contact_Demo/src/com/suntek/contact/MessageBoxList.java
package com.suntek.contact;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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.widget.ListView;
import android.widget.Toast;

import com.suntek.contact.adapter.MessageBoxListAdapter;
import com.suntek.contact.model.MessageBean;

/**
 * 短信消息列表 收发人
 * 
 * @author Administrator
 * 
 */
public class MessageBoxList extends Activity {
	private ListView talkView;
	private List messages = null;
	private AsyncQueryHandler asyncQuery;
	private String address;
	private SimpleDateFormat sdf;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_list_view);
		sdf = new SimpleDateFormat("MM-dd HH:mm");
		String thread = getIntent().getStringExtra("threadId");
		init(thread);
	}

	private void init(String thread) {
		asyncQuery = new MessageAsynQueryHandler(getContentResolver());
		talkView = (ListView) findViewById(R.id.message_list);
		messages = new ArrayList();

		Uri uri = Uri.parse("content://sms");
		String[] projection = new String[] { "date", "address", "person",
				"body", "type" }; // 查询的列
		asyncQuery.startQuery(0, null, uri, projection,
				"thread_id = " + thread, null, "date asc");
	}

	/**
	 * 异步查询数据库的类
	 * 
	 * @author Administrator
	 * 
	 */
	private class MessageAsynQueryHandler extends AsyncQueryHandler {

		public MessageAsynQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					String date = sdf.format(new Date(cursor.getLong(cursor
							.getColumnIndex("date"))));
					if (cursor.getInt(cursor.getColumnIndex("type")) == 1) {// 他说的信息
						MessageBean d = new MessageBean(
								cursor.getString(cursor
										.getColumnIndex("address")),
								date,
								cursor.getString(cursor.getColumnIndex("body")),
								R.layout.list_say_he_item);
						messages.add(d);
					} else { // 我说的信息
						MessageBean d = new MessageBean(
								cursor.getString(cursor
										.getColumnIndex("address")),
								date,
								cursor.getString(cursor.getColumnIndex("body")),
								R.layout.list_say_me_item);
						messages.add(d);
					}
				}
				if (messages.size() > 0) {
					talkView.setAdapter(new MessageBoxListAdapter(
							MessageBoxList.this, messages));
					talkView.setDivider(null);
					talkView.setSelection(messages.size());
				} else {
					Toast.makeText(MessageBoxList.this, "没有短信进行操作",
							Toast.LENGTH_SHORT).show();
				}
			}
			super.onQueryComplete(token, cookie, cursor);
		}
	}
}




你可能感兴趣的:(Android通讯录管理(获取联系人、通话记录、短信消息)(三))