Android开发学习之电话、短信、联系人

        作为一部手机,最重要的功能当属电话、短信、联系人了,所以今天想和大家分享的是关于Android电话、短信、联系人这块的API接口。

        1、通话记录的获取

        List<TelePhoneRecord> mRecords=new ArrayList<TelePhoneRecord>();
    	Cursor mCursor=mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null,null, null,null);
    	if(mCursor!=null && mCursor.moveToFirst())
    	{
    		do
    		{
    		    TelePhoneRecord.getColumnIndex(mCursor);
    		    TelePhoneRecord mRecord=new TelePhoneRecord(mCursor);
    		    mRecords.add(mRecord);
    		}while(mCursor.moveToNext());
    	}
    	mCursor.close();

      其中TelephoneRecord是对通话记录的一个实体类,定义如下:

/*
 * 通话记录描述类
 */
package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class TelePhoneRecord 
{
   /**通话记录ID **/
   private long mID;
   /**电话号码    **/
   private String mNumber;
   /**通话日期   **/
   private long mDate;
   /** 通话类型  **/
   private long mType;
   /*
    * 1:来电
    * 2:去电
    */
   private long mDuration;
   
   
   
   
   /**通话记录ID索引**/
   private static int Index_ID;
   /** 电话号码索引**/
   private static int Index_Number;
   /** 通话日期索引 **/
   private static int Index_Date;
   /** 通话类型索引 **/
   private static int Index_Type;
   /** 通话时间索引 **/
   private static int Index_Duration;
   
   
   public static void getColumnIndex(Cursor c)
   {
	   Index_ID=c.getColumnIndex("_id");
	   Index_Number=c.getColumnIndex("number");
	   Index_Date=c.getColumnIndex("date");
	   Index_Type=c.getColumnIndex("type");
	   Index_Duration=c.getColumnIndex("duration");
   }
   
   public TelePhoneRecord(Cursor c)
   {
	   mID=c.getLong(Index_ID);
	   mNumber=c.getString(Index_Number);
	   mDate=c.getLong(Index_Date);
	   mType=c.getLong(Index_Type);
	   mDuration=c.getLong(Index_Duration);
   }
   
   public long getID() {
	return mID;
   }
   
   public void setID(long mID) {
	this.mID = mID;
   }
   
   public String getNumber() {
	return mNumber;
   }
   
   public void setNumber(String mNumber) {
	this.mNumber = mNumber;
   }
   
   public long getDate() {
	return mDate;
   }
   
   public void setDate(long mDate) {
	this.mDate = mDate;
   }
   
   public long getType() {
	return mType;
   }
   
   public void setType(long mType) {
	this.mType = mType;
   }

   public long getDuration() {
	return mDuration;
   }

   public void setDuration(long mDuration) {
	this.mDuration = mDuration;
   }
}

        2、来电、去电、短线的监听

        监听来电:继承BoardcastReciver在onReceive方法中判断Intent的类型或者使用TelephoneManager获取电话状态

        监听去电:继承BoardcastReciver在onReceive方法中判断Intent的类型

        监听短信:在BoardcastReciver中,从Bundle中获取pdus数据,转换为SmsMessage对象

        3、读取联系人

	   List<Contact> mContacts=new ArrayList<Contact>();
	   //此路径只能查询联系人名称
	   /*Cursor c1=mContext.getContentResolver().query(Uri.withAppendedPath(ContactsContract.AUTHORITY_URI,
			   "contacts"), null, null, null, null);*/
	   //此路径可以查询联系人名称和号码
	   Cursor c2=mContext.getContentResolver().query(Uri.withAppendedPath(ContactsContract.AUTHORITY_URI,
			   "data/phones"), null, null, null, null);
	   if(c2!=null && c2.moveToFirst())
	   {
		   do
		   {
			   Contact.getColumnIndex(c2);
			   Contact mContact=new Contact(c2);
			   mContacts.add(mContact);
		   }while(c2.moveToNext());
	   }
	   c2.close();
           同样给出Contact的定义:

package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class Contact 
{
   private String mName;
   private String mNum;
   
   private static int Index_Name;
   private static int Index_Num;
   
   public static void getColumnIndex(Cursor c)
   {
	   Index_Name=c.getColumnIndex("display_name");
	   Index_Num=c.getColumnIndex("data1");
   }
   
   public Contact(Cursor c)
   {
	   mName=c.getString(Index_Name);
	   mNum=c.getString(Index_Num);
   }
   
   public String getName() {
	return mName;
   }
   
   public void setName(String mName) {
	this.mName = mName;
   }
   
   public String getNum() {
	return mNum;
   }
   
   public void setNum(String mNum) {
	this.mNum = mNum;
   }
}
        4、增加联系人

	   ContentValues mValues=new ContentValues();
	   //获取RawContactID
	   Uri mRawContactUri=mContext.getContentResolver().insert(RawContacts.CONTENT_URI, mValues);
	   long mRawContactID=ContentUris.parseId(mRawContactUri);
	   mValues.clear();
	   //设置RawContactID
	   mValues.put(StructuredName.RAW_CONTACT_ID, mRawContactID);
	   //设置MIMETYPE
	   mValues.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
	   //设置联系人姓名
	   mValues.put(StructuredName.DISPLAY_NAME, Name);
	   //插入联系人姓名信息
	   mContext.getContentResolver().insert(Data.CONTENT_URI, mValues);
	   
	   mValues.clear();
	   //设置RawContactID
	   mValues.put(Phone.RAW_CONTACT_ID, mRawContactID);
	   //设置MIMETYPE
	   mValues.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
	   //设置联系人号码
	   
	   mValues.put(Phone.NUMBER, Num);
	   //插入联系人号码信息
	   mContext.getContentResolver().insert(Data.CONTENT_URI, mValues);
         5、短信读取

/*
 * 短信读取工具类
 * @author:秦元培
 * 时间:2014年1月23日
 */
package com.android.TelephoneAPIs.Tools;

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

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

public class ShortMessageReader 
{
	/** 定义收件箱查询地址  **/
	public static final Uri SMS_INBOX=Uri.parse("content://sms/inbox");
	/** 定义所有信息查询地址 **/
	public static final Uri SMS_ALL=Uri.parse("content://sms");
	/** 定义发件箱查询地址  **/
	public static final Uri SMS_TOBOX=Uri.parse("content://sms/sent");
	
	
	
	/** 获取所有的短消息**/
	public static List<ShortMessage>  getAllMessages(Context mContext)
	{
    	List<ShortMessage> Messages=new ArrayList<ShortMessage>();
    	Messages=queryMessage(mContext,SMS_ALL, null,null);
    	return Messages;
	}
	
	
	/** 获取指定号码的短消息   **/
    public static List<ShortMessage> getMessageByNumber(Context mContext,Uri mUri,String[]mSelectionAns)
    {
    	List<ShortMessage> Messages=new ArrayList<ShortMessage>();
    	Messages=queryMessage(mContext, mUri, "address=?",mSelectionAns);
    	return Messages;
    }
    
    /** 获取指定会话ID的短消息    **/
    public static List<ShortMessage> getMessageByThreadID(Context mContext,Uri mUri,String[]mSelectionAns)
    {
    	List<ShortMessage> Messages=new ArrayList<ShortMessage>();
    	Messages=queryMessage(mContext, mUri, "thread_id=?",mSelectionAns);
    	return Messages;
    }
    
    
    /** 获取任何满足条件的短消息    **/
    public static List<ShortMessage> queryMessage(Context mContext,Uri mUri,String mSelection,String[]mSelectionAns)
    {
    	List<ShortMessage> Messages=new ArrayList<ShortMessage>();
    	Cursor mCursor=mContext.getContentResolver().query(mUri, null,mSelection,mSelectionAns, null);
    	if(mCursor!=null && mCursor.moveToFirst())
    	{
    		do
    		{
    			ShortMessage.getColumnIndex(mCursor);
    		    ShortMessage mMessage=new ShortMessage(mCursor);
    			/** 添加到Messages **/
    			Messages.add(mMessage);
    		}while(mCursor.moveToNext());
    	}
    	mCursor.close();
		return Messages;
    }
}
          ShortMessage定义如下:

 package com.android.TelephoneAPIs.Tools;

import android.database.Cursor;

public class ShortMessage 
{
	
  /** 短消息会话ID **/
  private long mThreadID;
  /** 短消息Id **/
  private long mID;
  /** 短消息内容  **/
  private String mBody;
  /** 短消息主题  **/
  private String mSubject;
  /** 短消息发送时间  **/
  private long mDate;
  /** 短消息发送人号码  **/
  private String mAddress;
  /** 短消息发送人  **/
  private int mPerson;
  /** 短消息状态   **/
  private int mRead;
  /** 短消息类型  **/
  private int mType;
  
  /** 获取会话ID索引**/
  private static int Index_Thread_ID;
  /** 获取ID索引**/
  private static int Index_ID;
  /** 获取地址索引  **/
  private static int Index_Address;
  /** 获取时间索引  **/
  private static int Index_Date;
  /** 获取主题索引 **/
  private static int Index_Subject;
  /** 获取内容索引 **/
  private static int Index_Body;
  /** 获取发送人索引  **/
  private static int Index_Person;
  /** 获取状态索引  **/
  private static int Index_Read;
  /** 获取类型索引  **/
  private static int Index_Type;
  
  
  public ShortMessage(Cursor c)
  {
	  /** 获取会话ID **/
	  mThreadID=c.getLong(Index_Thread_ID);
	  /** 获取ID **/
	  mID=c.getLong(Index_ID);
	  /** 获取Address **/
	  mAddress=c.getString(Index_Address);
	  /** 获取Subject **/
	  mSubject=c.getString(Index_Subject);
	  /** 获取Date **/
	  mDate=c.getLong(Index_Date);
	  /** 获取Body **/
	  mBody=c.getString(Index_Body);
	  /** 获取Person **/
	  mPerson=c.getInt(Index_Person);
	  /** 获取Read **/
	  mRead=c.getInt(Index_Read);
	  /** 获取Type **/
	  mType=c.getInt(Index_Type);
  }
  
  public static void getColumnIndex(Cursor c)
  {
	    /** 获取会话ID索引**/
		Index_Thread_ID=c.getColumnIndex("thread_id");
		/** 获取ID索引**/
		Index_ID=c.getColumnIndex("_id");
		/** 获取地址索引  **/
		Index_Address=c.getColumnIndex("address");
		/** 获取时间索引  **/
		Index_Date=c.getColumnIndex("date");
		/** 获取主题索引 **/
		Index_Subject=c.getColumnIndex("subject");
		/** 获取内容索引 **/
		Index_Body=c.getColumnIndex("body");
		/** 获取发送人索引  **/
		Index_Person=c.getColumnIndex("person");
		/** 获取状态索引  **/
		Index_Read=c.getColumnIndex("read");
		/** 获取类型索引  **/
		Index_Type=c.getColumnIndex("type");
  }
  
  public long getThreadID() {
	return mThreadID;
  }
  
  public void setThreadID(long mThreadID) {
	this.mThreadID = mThreadID;
  }
  
  public long getID() {
	return mID;
  }
  
  public void setID(long mID) {
	this.mID = mID;
  }
  
  public String getBody() {
	return mBody;
  }
  
  public void setBody(String mBody) {
	this.mBody = mBody;
  }
  
  public long getDate() {
 	return mDate;
  }
  
  public void setDate(long mDate) {
	this.mDate = mDate;
  }
  
  public String getAddress() {
	return mAddress;
  }
  
  public void setAddress(String mAddress) {
	this.mAddress = mAddress;
  }
  
  public long getRead() {
	return mRead;
  }
  
  public void setRead(int mRead) {
	this.mRead = mRead;
  }

  public long getPerson() {
	return mPerson;
  }

  public void setPerson(int mPerson) {
	this.mPerson = mPerson;
  }

  public String getSubject() {
	return mSubject;
  }

  public void setSubject(String mSubject) {
	this.mSubject = mSubject;
  }

  public long getType() {
	return mType;
  }

  public void setType(int mType) {
	this.mType = mType;
  }
  
}

        6、短信发送

 public static void sendMessage(Context mContext,String mNum,String mContent,boolean mSave)
   {
	   if(mSave)
	   {
	     SmsManager mManager=SmsManager.getDefault();
	     mManager.sendTextMessage(mNum, null, mContent, null, null);
	     ContentValues mValues=new ContentValues();
	     mValues.put("thread_id",getThreadIDByAddress(mContext,new String[]{mNum}));
	     mValues.put("body", mContent);
	     mValues.put("date", new Date().getTime());
	     mValues.put("address", mNum);
	     mValues.put("type", 2);
	     mValues.put("read", 1);
	     mContext.getContentResolver().insert(Uri.parse("content://sms"), mValues);
	   }else{
		 SmsManager mManager=SmsManager.getDefault();
		 mManager.sendTextMessage(mNum, null, mContent, null, null);
	   }
	   
   }
	   private static long getThreadIDByAddress(Context mContext,String[] SelectionArg)
	   {
		   List<ShortMessage> mMessages=ShortMessageReader.getMessageByNumber(mContext, ShortMessageReader.SMS_INBOX,SelectionArg );
		   ShortMessage m=mMessages.get(0);
		   return m.getThreadID();
	   }

          上面的两个方法分别是发送短信和获取短线会话ID的方法,可以设定是否保存到数据库中

          7、将短信以Xml文件形式导出

 public static void OutputByXml(List<ShortMessage> mMessages,String mXmlFilePath)
   {
	   File XmlFile = new File(mXmlFilePath);  
       try{  
    	   XmlFile.createNewFile();  
       }catch (IOException e) {  
           e.printStackTrace();
       }  
       FileOutputStream fos = null;  
       try{  
           fos = new FileOutputStream(XmlFile);  
       }catch (FileNotFoundException  e) {  
          e.printStackTrace();
       }  
       XmlSerializer serializer = Xml.newSerializer();  
       try {  
           serializer.setOutput(fos,"UTF-8");  
           serializer.startDocument(null, true);  
           serializer.startTag(null, "ShortMessages");  
           for(int i = 0; i < mMessages.size(); i ++){  
               serializer.startTag(null, "Message");  
               serializer.startTag(null, "Address");  
               serializer.text(mMessages.get(i).getAddress());  
               serializer.endTag(null, "Address");  
               serializer.startTag(null, "Body");  
               serializer.text(mMessages.get(i).getBody());  
               serializer.endTag(null, "Body");  
               serializer.endTag(null, "Message");  
           }  
           serializer.endTag(null, "ShortMessages");  
           serializer.endDocument();  
           serializer.flush();  
           fos.close();  
       } catch (Exception e) {  
          e.printStackTrace();
       }  
   }

         以上代码全部测试通过,所需权限如下:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>




  

Android开发学习之电话、短信、联系人,布布扣,bubuko.com

Android开发学习之电话、短信、联系人

上一篇:【Android】从源码中探讨Handler机制


下一篇:针对android方法数64k的限制,square做出的努力