下面从设计短信程序设计过程来介绍一下Android手机上的短信功能。
一、短信权限
发送短信权限
读取短信权限
写入短信权限
接收短信权限
二、短信广播
手机在接收到短信后会发出一条广播,如果需要对接收到的短信进行处理需要注册该广播的接收器。
三、短信存储
Android手机中的短信保存在数据库中,用ContentProvider来共享数据。数据库文件为/dbdata/databases/com.android.providers.telephony/mmssms.db,用DDMS可以查看。
四、获取短信
分成两种,一种是通过监听广播来获取,另外一种是直接读取数据库中的内容。下面以接收短信分别介绍一下。
1、监听广播
这种方式只有在接收到新短信时才会触发。新短信的定义为,向系统收件箱中写入短信,包括接收短信写入和人为写入短信。这种方法需要注册广播接收器,注册方法有两种,一种在xml文件中注册,另外一种是在代码中注册。
广播接收器:
Java代码
xml文件内容
添加到AndroidManifest.xml文件中
或者在代码中实现
广播接收器实例化
注册监听器
2、读数据库
代码来源:http://blog.csdn.net/sunboy_2050/article/details/7328321
上述代码涉及ContentProvider的操作,另外有相关资料介绍可从数据库端来监听短信收发,相关代码如下(http://lyp2002924.iteye.com/blog/491718):
五、发送短信
有两种方法,一种是调用短信接口,另外一种是调用系统发送短信的功能
1、短信接口
2、系统功能
应用比较方便的是第一种方法。另外针对短信的发送状态和接收状态也可以做相应处理。
返回的发送状态处理:
返回的接收状态处理:
六、代码实例
该实例代码可以显示接收到的短信,也可以发送短信并显示发送的内容。
运行效果图:
一、短信权限
发送短信权限
01
|
<
uses-permission
android:name
=
"android.permission.SEND_SMS"
/>
|
读取短信权限
01
|
<
uses-permission
android:name
=
"android.permission.READ_SMS"
/>
|
写入短信权限
01
|
<
uses-permission
android:name
=
"android.permission.WRITE_SMS"
/>
|
接收短信权限
01
|
<
uses-permission
android:name
=
"android.permission.RECEIVE_SMS"
/>
|
二、短信广播
手机在接收到短信后会发出一条广播,如果需要对接收到的短信进行处理需要注册该广播的接收器。
三、短信存储
Android手机中的短信保存在数据库中,用ContentProvider来共享数据。数据库文件为/dbdata/databases/com.android.providers.telephony/mmssms.db,用DDMS可以查看。
四、获取短信
分成两种,一种是通过监听广播来获取,另外一种是直接读取数据库中的内容。下面以接收短信分别介绍一下。
1、监听广播
这种方式只有在接收到新短信时才会触发。新短信的定义为,向系统收件箱中写入短信,包括接收短信写入和人为写入短信。这种方法需要注册广播接收器,注册方法有两种,一种在xml文件中注册,另外一种是在代码中注册。
广播接收器:
Java代码
01
02
03
04
05
06
|
public
class
SMSReceiver
extends
BroadcastReceiver {
@Override
public
void
onReceive(Context context, Intent intent) {
// TODO
}
}
|
xml文件内容
添加到AndroidManifest.xml文件中
01
02
03
04
05
|
<
receiver
android:name=”.receiver.SMSReceiver” android:enabled=”true”>
<
intent-filter
>
<
action
android:name=”android.provider.Telephony.SMS_RECEIVED” />
</
intent-filter
>
</
receiver
>
|
或者在代码中实现
广播接收器实例化
01
02
03
04
05
06
07
08
09
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
|
private
BroadcastReceiver SMSreceiver=
new
BroadcastReceiver(){
@Override
public
void
onReceive(Context context, Intent intent)
{
if
(
"android.provider.Telephony.SMS_RECEIVED"
.equals(intent.getAction()))
{
SimpleDateFormat formatter =
new
SimpleDateFormat(
"yyyy年MM月dd日HH:mm:ss"
);
Date curDate =
new
Date(System.currentTimeMillis());
messagedate = formatter.format(curDate);
StringBuilder sb =
new
StringBuilder();
// 接收由SMS传过来的数据
Bundle bundle = intent.getExtras();
// 判断是否有数据
if
(bundle !=
null
)
{
// 通过pdus可以获得接收到的所有短信消息
Object[] objArray = (Object[]) bundle.get(
"pdus"
);
/* 构建短信对象array,并依据收到的对象长度来创建array的大小 */
SmsMessage[] messages = new SmsMessage[objArray.length];
for (int i = 0; i < objArray.length; i++)
{
messages<i> = SmsMessage.createFromPdu((byte[]) objArray<i>);
}
/* 将送来的短信合并自定义信息于StringBuilder当中 */
for
(SmsMessage currentMessage : messages)
{
sb.append(
"短信来源:"
);
// 获得接收短信的电话号码
sb.append(currentMessage.getDisplayOriginatingAddress());
sb.append(
"\n------短信内容------\n"
);
// 获得短信的内容
sb.append(currentMessage.getDisplayMessageBody());
}
}
Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
}
}
};</i></i>
|
注册监听器
01
02
03
04
05
06
07
|
//过滤器
IntentFilter intentFilter =
new
IntentFilter();
intentFilter.addAction(
"android.provider.Telephony.SMS_RECEIVED"
);
//设置优先级
intentFilter.setPriority(
500
);
//注册监听器
registerReceiver(SMSreceiver, intentFilter);
|
2、读数据库
01
02
03
04
05
06
07
08
09
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
|
public
String getSmsInPhone() {
final
String SMS_URI_ALL =
"content://sms/"
;
final
String SMS_URI_INBOX =
"content://sms/inbox"
;
final
String SMS_URI_SEND =
"content://sms/sent"
;
final
String SMS_URI_DRAFT =
"content://sms/draft"
;
final
String SMS_URI_OUTBOX =
"content://sms/outbox"
;
final
String SMS_URI_FAILED =
"content://sms/failed"
;
final
String SMS_URI_QUEUED =
"content://sms/queued"
;
StringBuilder smsBuilder =
new
StringBuilder();
try
{
Uri uri = Uri.parse(SMS_URI_ALL);
String[] projection =
new
String[] {
"_id"
,
"address"
,
"person"
,
"body"
,
"date"
,
"type"
};
Cursor cur = getContentResolver().query(uri, projection,
null
,
null
,
"date desc"
);
// 获取手机内部短信
if
(cur.moveToFirst()) {
int
index_Address = cur.getColumnIndex(
"address"
);
int
index_Person = cur.getColumnIndex(
"person"
);
int
index_Body = cur.getColumnIndex(
"body"
);
int
index_Date = cur.getColumnIndex(
"date"
);
int
index_Type = cur.getColumnIndex(
"type"
);
do
{
String strAddress = cur.getString(index_Address);
int
intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
long
longDate = cur.getLong(index_Date);
int
intType = cur.getInt(index_Type);
SimpleDateFormat dateFormat =
new
SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss"
);
Date d =
new
Date(longDate);
String strDate = dateFormat.format(d);
String strType =
""
;
if
(intType ==
1
) {
strType =
"接收"
;
}
else
if
(intType ==
2
) {
strType =
"发送"
;
}
else
{
strType =
"null"
;
}
smsBuilder.append(
"[ "
);
smsBuilder.append(strAddress +
", "
);
smsBuilder.append(intPerson +
", "
);
smsBuilder.append(strbody +
", "
);
smsBuilder.append(strDate +
", "
);
smsBuilder.append(strType);
smsBuilder.append(
" ]\n\n"
);
}
while
(cur.moveToNext());
if
(!cur.isClosed()) {
cur.close();
cur =
null
;
}
}
else
{
smsBuilder.append(
"no result!"
);
}
// end if
smsBuilder.append(
"getSmsInPhone has executed!"
);
}
catch
(SQLiteException ex) {
Log.d(
"SQLiteException in getSmsInPhone"
, ex.getMessage());
}
return
smsBuilder.toString();
}
|
代码来源:http://blog.csdn.net/sunboy_2050/article/details/7328321
上述代码涉及ContentProvider的操作,另外有相关资料介绍可从数据库端来监听短信收发,相关代码如下(http://lyp2002924.iteye.com/blog/491718):
01
02
03
04
05
06
07
08
09
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
|
//如下 主要用于内部数据库改变,向外面的界面(Activity)做反应
class
SMSHandler
extends
Handler
{
public
void
handleMessage(Message msg)
{
//Handle message
}
}
// 对收到短消息后,做出的处理,这里直接删除,并没有反应到界面,所以上面的handleMessage是空的。
class
SMSObserver
extends
ContentObserver
{
private
Handle m_handle =
null
;
public
SMSObserver(Handle handle)
{
super
(handle);
m_handle = handle;
}
public
void
onChange(
boolean
bSelfChange)
{
super
.onChange(bSelfChange);
//Send message to Activity
Message msg =
new
Message();
msg.obj =
"xxxxxxxxxx"
;
m_handle.sendMessage(msg);
String strUriInbox =
"content://sms/inbox"
;
Uri uriSms = Uri.parse(strUriInbox);
//If you want to access all SMS, just replace the uri string to "content://sms/"
Cursor c = mContext.getContentResolver().query(uriSms,
null
,
null
,
null
,
null
);
// delete all sms here when every new sms occures.
while
(c.moveToNext())
{
//Read the contents of the SMS;
for
(
int
i; i < c.getColumnCount(); i++)
{
String strColumnName = c.getColumnName(i);
String strColumnValue = c.getString(i);
}
//Delete the SMS
String uri =
"content://sms"
;
mContext.getContentResolver().delete(Uri.parse(uri),
null
,
null
);
}
}
}
//把基本类功能性地应用起来
ContentResolver contentResolver = getContentResolver();
// Context 环境下getContentResolver()
Handler handler =
new
SMSHandler();
ContentObserver m_SMSObserver =
new
SMSObserver(handler);
contentResolver.registerContentObserver(Uri.parse(
"content://sms"
),
true
, m_SMSObserver);
//Register to observe SMS in outbox,we can observe SMS in other location by changing Uri string, such as inbox, sent, draft, outbox, etc.)
// some Available Uri string for sms.
/*
String strUriInbox = "content://sms/inbox";//SMS_INBOX:1
String strUriFailed = "content://sms/failed";//SMS_FAILED:2
String strUriQueued = "content://sms/queued";//SMS_QUEUED:3
String strUriSent = "content://sms/sent";//SMS_SENT:4
String strUriDraft = "content://sms/draft";//SMS_DRAFT:5
String strUriOutbox = "content://sms/outbox";//SMS_OUTBOX:6
String strUriUndelivered = "content://sms/undelivered";//SMS_UNDELIVERED
String strUriAll = "content://sms/all";//SMS_ALL
String strUriConversations = "content://sms/conversations";//you can delete one conversation by thread_id
String strUriAll = "content://sms"//you can delete one message by _id
*/
|
五、发送短信
有两种方法,一种是调用短信接口,另外一种是调用系统发送短信的功能
1、短信接口
01
02
03
04
05
06
07
|
//直接调用短信接口发短信
SmsManager smsManager = SmsManager.getDefault();
String PhoneNumber=
"189XXXX3456"
;
List<String> divideContents = smsManager.divideMessage(content);
for
(String text : divideContents) {
smsManager.sendTextMessage(PhoneNumber,
null
, text, sentPI, deliverPI);
}
|
2、系统功能
01
02
03
04
05
06
|
String PhoneNumber=
"smsto:10086"
;
String messagebody=
"This is the message's body!"
Uri uri = Uri.parse(PhoneNumber)
Intent it =
new
Intent(Intent.ACTION_SENDTO, uri);
it.putExtra(
"sms_body"
, messagebody);
activity.startActivity(it);
|
应用比较方便的是第一种方法。另外针对短信的发送状态和接收状态也可以做相应处理。
返回的发送状态处理:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
String SENT_SMS_ACTION =
"SENT_SMS_ACTION"
;
Intent sentIntent =
new
Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(context,
0
, sentIntent,
0
);
// register the Broadcast Receivers
context.registerReceiver(
new
BroadcastReceiver() {
@Override
public
void
onReceive(Context _context, Intent _intent) {
switch
(getResultCode()) {
case
Activity.RESULT_OK:
Toast.makeText(context,
"短信发送成功"
, Toast.LENGTH_SHORT)
.show();
break
;
case
SmsManager.RESULT_ERROR_GENERIC_FAILURE:
break
;
case
SmsManager.RESULT_ERROR_RADIO_OFF:
break
;
case
SmsManager.RESULT_ERROR_NULL_PDU:
break
;
}
}
},
new
IntentFilter(SENT_SMS_ACTION));
|
返回的接收状态处理:
01
02
03
04
05
06
07
08
09
10
11
12
13
|
String DELIVERED_SMS_ACTION =
"DELIVERED_SMS_ACTION"
;
// create the deilverIntent parameter
Intent deliverIntent =
new
Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI = PendingIntent.getBroadcast(context,
0
,
deliverIntent,
0
);
context.registerReceiver(
new
BroadcastReceiver() {
@Override
public
void
onReceive(Context _context, Intent _intent) {
Toast.makeText(context,
"收信人已经成功接收"
, Toast.LENGTH_SHORT)
.show();
}
},
new
IntentFilter(DELIVERED_SMS_ACTION));
|
六、代码实例
该实例代码可以显示接收到的短信,也可以发送短信并显示发送的内容。
运行效果图: