史上最全系列之设备功能之短信

下面从设计短信程序设计过程来介绍一下Android手机上的短信功能。
一、短信权限
发送短信权限
代码片段,双击复制
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可以查看。
表名 访问数据库的uri
版本 X1
uri 内容
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿箱
content://sms/outbox 发件箱
content://sms/failed 发送失败
content://sms/queued 待发送序列

表名 数据库相关字段
版本 X1
字段名 内容
_id 一个自增字段,从1开始
thread_id 收件人编号
address 收件人手机号码
person 联系人列表里的序号,陌生人为null
date 发件日期,单位是milliseconds,从1970/01/01至今所经过的时间
protocol 协议,分为: 0 SMS_RPOTO, 1 MMS_PROTO
read 是否阅读,0未读, 1已读
status 状态,,-1接收,0 complete, 64 pending, 128失败
type ALL= 0,INBOX  = 1,SENT   = 2,DRAFT  = 3,OUTBOX = 4,FAILED = 5,QUEUED = 6
body 短信内容
service_center 短信服务中心号码编号
subject 短信主题
reply_path_present 应答路径(TP-Reply-Path)
locked 短信是否锁定

四、获取短信
分成两种,一种是通过监听广播来获取,另外一种是直接读取数据库中的内容。下面以接收短信分别介绍一下。
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));

六、代码实例
该实例代码可以显示接收到的短信,也可以发送短信并显示发送的内容。
运行效果图:

在使用Python来安装geopandas包时,由于geopandas依赖于几个其他的Python库(如GDAL, Fiona, Pyproj, Shapely等),因此安装过程可能需要一些额外的步骤。以下是一个基本的安装指南,适用于大多数用户: 使用pip安装 确保Python和pip已安装: 首先,确保你的计算机上已安装了Python和pip。pip是Python的包管理工具,用于安装和管理Python包。 安装依赖库: 由于geopandas依赖于GDAL, Fiona, Pyproj, Shapely等库,你可能需要先安装这些库。通常,你可以通过pip直接安装这些库,但有时候可能需要从其他源下载预编译的二进制包(wheel文件),特别是GDAL和Fiona,因为它们可能包含一些系统级的依赖。 bash pip install GDAL Fiona Pyproj Shapely 注意:在某些系统上,直接使用pip安装GDAL和Fiona可能会遇到问题,因为它们需要编译一些C/C++代码。如果遇到问题,你可以考虑使用conda(一个Python包、依赖和环境管理器)来安装这些库,或者从Unofficial Windows Binaries for Python Extension Packages这样的网站下载预编译的wheel文件。 安装geopandas: 在安装了所有依赖库之后,你可以使用pip来安装geopandas。 bash pip install geopandas 使用conda安装 如果你正在使用conda作为你的Python包管理器,那么安装geopandas和它的依赖可能会更简单一些。 创建一个新的conda环境(可选,但推荐): bash conda create -n geoenv python=3.x anaconda conda activate geoenv 其中3.x是你希望使用的Python版本。 安装geopandas: 使用conda-forge频道来安装geopandas,因为它提供了许多地理空间相关的包。 bash conda install -c conda-forge geopandas 这条命令会自动安装geopandas及其所有依赖。 注意事项 如果你在安装过程中遇到任何问题,比如编译错误或依赖问题,请检查你的Python版本和pip/conda的版本是否是最新的,或者尝试在不同的环境中安装。 某些库(如GDAL)可能需要额外的系统级依赖,如地理空间库(如PROJ和GEOS)。这些依赖可能需要单独安装,具体取决于你的操作系统。 如果你在Windows上遇到问题,并且pip安装失败,尝试从Unofficial Windows Binaries for Python Extension Packages网站下载相应的wheel文件,并使用pip进行安装。 脚本示例 虽然你的问题主要是关于如何安装geopandas,但如果你想要一个Python脚本来重命名文件夹下的文件,在原始名字前面加上字符串"geopandas",以下是一个简单的示例: python import os # 指定文件夹路径 folder_path = 'path/to/your/folder' # 遍历文件夹中的文件 for filename in os.listdir(folder_path): # 构造原始文件路径 old_file_path = os.path.join(folder_path, filename) # 构造新文件名 new_filename = 'geopandas_' + filename # 构造新文件路径 new_file_path = os.path.join(folder_path, new_filename) # 重命名文件 os.rename(old_file_path, new_file_path) print(f'Renamed "{filename}" to "{new_filename}"') 请确保将'path/to/your/folder'替换为你想要重命名文件的实际文件夹路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值