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

来源:互联网 发布:淘宝怎么延长付款 编辑:程序博客网 时间:2024/05/16 12:23

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

1、通话记录的获取

?
1
2
3
4
5
6
7
8
9
10
11
12
13
        List<telephonerecord> mRecords=newArrayList<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=newTelePhoneRecord(mCursor);
                mRecords.add(mRecord);
            }while(mCursor.moveToNext());
        }
        mCursor.close();
</telephonerecord></telephonerecord>

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * 通话记录描述类
 */
packagecom.android.TelephoneAPIs.Tools;
 
importandroid.database.Cursor;
 
publicclass TelePhoneRecord
{
   /**通话记录ID **/
   privatelong mID;
   /**电话号码    **/
   privateString mNumber;
   /**通话日期   **/
   privatelong mDate;
   /** 通话类型  **/
   privatelong mType;
   /*
    * 1:来电
    * 2:去电
    */
   privatelong mDuration;
    
    
    
    
   /**通话记录ID索引**/
   privatestatic int Index_ID;
   /** 电话号码索引**/
   privatestatic int Index_Number;
   /** 通话日期索引 **/
   privatestatic int Index_Date;
   /** 通话类型索引 **/
   privatestatic int Index_Type;
   /** 通话时间索引 **/
   privatestatic int Index_Duration;
    
    
   publicstatic 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");
   }
    
   publicTelePhoneRecord(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);
   }
    
   publiclong getID() {
    returnmID;
   }
    
   publicvoid setID(longmID) {
    this.mID = mID;
   }
    
   publicString getNumber() {
    returnmNumber;
   }
    
   publicvoid setNumber(String mNumber) {
    this.mNumber = mNumber;
   }
    
   publiclong getDate() {
    returnmDate;
   }
    
   publicvoid setDate(longmDate) {
    this.mDate = mDate;
   }
    
   publiclong getType() {
    returnmType;
   }
    
   publicvoid setType(longmType) {
    this.mType = mType;
   }
 
   publiclong getDuration() {
    returnmDuration;
   }
 
   publicvoid setDuration(longmDuration) {
    this.mDuration = mDuration;
   }
}

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

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

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

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

3、读取联系人

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
List<contact> mContacts=newArrayList<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=newContact(c2);
        mContacts.add(mContact);
    }while(c2.moveToNext());
}
c2.close();</contact></contact>
同样给出Contact的定义:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
packagecom.android.TelephoneAPIs.Tools;
 
importandroid.database.Cursor;
 
publicclass Contact
{
   privateString mName;
   privateString mNum;
    
   privatestatic int Index_Name;
   privatestatic int Index_Num;
    
   publicstatic void getColumnIndex(Cursor c)
   {
       Index_Name=c.getColumnIndex("display_name");
       Index_Num=c.getColumnIndex("data1");
   }
    
   publicContact(Cursor c)
   {
       mName=c.getString(Index_Name);
       mNum=c.getString(Index_Num);
   }
    
   publicString getName() {
    returnmName;
   }
    
   publicvoid setName(String mName) {
    this.mName = mName;
   }
    
   publicString getNum() {
    returnmNum;
   }
    
   publicvoid setNum(String mNum) {
    this.mNum = mNum;
   }
}
4、增加联系人

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ContentValues mValues=newContentValues();
//获取RawContactID
Uri mRawContactUri=mContext.getContentResolver().insert(RawContacts.CONTENT_URI, mValues);
longmRawContactID=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、短信读取

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * 短信读取工具类
 * @author:秦元培
 * 时间:2014年1月23日
 */
packagecom.android.TelephoneAPIs.Tools;
 
importjava.util.ArrayList;
importjava.util.List;
 
importandroid.content.Context;
importandroid.database.Cursor;
importandroid.net.Uri;
 
publicclass ShortMessageReader
{
    /** 定义收件箱查询地址  **/
    publicstatic final Uri SMS_INBOX=Uri.parse("content://sms/inbox");
    /** 定义所有信息查询地址 **/
    publicstatic final Uri SMS_ALL=Uri.parse("content://sms");
    /** 定义发件箱查询地址  **/
    publicstatic final Uri SMS_TOBOX=Uri.parse("content://sms/sent");
     
     
     
    /** 获取所有的短消息**/
    publicstatic List<shortmessage>  getAllMessages(Context mContext)
    {
        List<shortmessage> Messages=newArrayList<shortmessage>();
        Messages=queryMessage(mContext,SMS_ALL,null,null);
        returnMessages;
    }
     
     
    /** 获取指定号码的短消息   **/
    publicstatic List<shortmessage> getMessageByNumber(Context mContext,Uri mUri,String[]mSelectionAns)
    {
        List<shortmessage> Messages=newArrayList<shortmessage>();
        Messages=queryMessage(mContext, mUri, "address=?",mSelectionAns);
        returnMessages;
    }
     
    /** 获取指定会话ID的短消息    **/
    publicstatic List<shortmessage> getMessageByThreadID(Context mContext,Uri mUri,String[]mSelectionAns)
    {
        List<shortmessage> Messages=newArrayList<shortmessage>();
        Messages=queryMessage(mContext, mUri, "thread_id=?",mSelectionAns);
        returnMessages;
    }
     
     
    /** 获取任何满足条件的短消息    **/
    publicstatic List<shortmessage> queryMessage(Context mContext,Uri mUri,String mSelection,String[]mSelectionAns)
    {
        List<shortmessage> Messages=newArrayList<shortmessage>();
        Cursor mCursor=mContext.getContentResolver().query(mUri, null,mSelection,mSelectionAns,null);
        if(mCursor!=null&& mCursor.moveToFirst())
        {
            do
            {
                ShortMessage.getColumnIndex(mCursor);
                ShortMessage mMessage=newShortMessage(mCursor);
                /** 添加到Messages **/
                Messages.add(mMessage);
            }while(mCursor.moveToNext());
        }
        mCursor.close();
        returnMessages;
    }
}
</shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage></shortmessage>
ShortMessage定义如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
packagecom.android.TelephoneAPIs.Tools;
 
importandroid.database.Cursor;
 
publicclass ShortMessage
{
     
  /** 短消息会话ID **/
  privatelong mThreadID;
  /** 短消息Id **/
  privatelong mID;
  /** 短消息内容  **/
  privateString mBody;
  /** 短消息主题  **/
  privateString mSubject;
  /** 短消息发送时间  **/
  privatelong mDate;
  /** 短消息发送人号码  **/
  privateString mAddress;
  /** 短消息发送人  **/
  privateint mPerson;
  /** 短消息状态   **/
  privateint mRead;
  /** 短消息类型  **/
  privateint mType;
   
  /** 获取会话ID索引**/
  privatestatic int Index_Thread_ID;
  /** 获取ID索引**/
  privatestatic int Index_ID;
  /** 获取地址索引  **/
  privatestatic int Index_Address;
  /** 获取时间索引  **/
  privatestatic int Index_Date;
  /** 获取主题索引 **/
  privatestatic int Index_Subject;
  /** 获取内容索引 **/
  privatestatic int Index_Body;
  /** 获取发送人索引  **/
  privatestatic int Index_Person;
  /** 获取状态索引  **/
  privatestatic int Index_Read;
  /** 获取类型索引  **/
  privatestatic int Index_Type;
   
   
  publicShortMessage(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);
  }
   
  publicstatic 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");
  }
   
  publiclong getThreadID() {
    returnmThreadID;
  }
   
  publicvoid setThreadID(longmThreadID) {
    this.mThreadID = mThreadID;
  }
   
  publiclong getID() {
    returnmID;
  }
   
  publicvoid setID(longmID) {
    this.mID = mID;
  }
   
  publicString getBody() {
    returnmBody;
  }
   
  publicvoid setBody(String mBody) {
    this.mBody = mBody;
  }
   
  publiclong getDate() {
    returnmDate;
  }
   
  publicvoid setDate(longmDate) {
    this.mDate = mDate;
  }
   
  publicString getAddress() {
    returnmAddress;
  }
   
  publicvoid setAddress(String mAddress) {
    this.mAddress = mAddress;
  }
   
  publiclong getRead() {
    returnmRead;
  }
   
  publicvoid setRead(intmRead) {
    this.mRead = mRead;
  }
 
  publiclong getPerson() {
    returnmPerson;
  }
 
  publicvoid setPerson(intmPerson) {
    this.mPerson = mPerson;
  }
 
  publicString getSubject() {
    returnmSubject;
  }
 
  publicvoid setSubject(String mSubject) {
    this.mSubject = mSubject;
  }
 
  publiclong getType() {
    returnmType;
  }
 
  publicvoid setType(intmType) {
    this.mType = mType;
  }
   
}

6、短信发送

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
publicstatic void sendMessage(Context mContext,String mNum,String mContent,booleanmSave)
  {
      if(mSave)
      {
        SmsManager mManager=SmsManager.getDefault();
        mManager.sendTextMessage(mNum,null, mContent, null,null);
        ContentValues mValues=newContentValues();
        mValues.put("thread_id",getThreadIDByAddress(mContext,newString[]{mNum}));
        mValues.put("body", mContent);
        mValues.put("date",newDate().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);
      }
       
  }
      privatestatic long getThreadIDByAddress(Context mContext,String[] SelectionArg)
      {
          List<shortmessage> mMessages=ShortMessageReader.getMessageByNumber(mContext, ShortMessageReader.SMS_INBOX,SelectionArg );
          ShortMessage m=mMessages.get(0);
          returnm.getThreadID();
      }</shortmessage>

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
publicstatic void OutputByXml(List<shortmessage> mMessages,String mXmlFilePath)
  {
      File XmlFile = newFile(mXmlFilePath); 
      try
          XmlFile.createNewFile(); 
      }catch(IOException e) { 
          e.printStackTrace();
      
      FileOutputStream fos = null
      try
          fos = newFileOutputStream(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(inti = 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();
      
  }</shortmessage>

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

?
1
2
3
4
5
<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"></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission>

0 0
原创粉丝点击