SMS
Android SMS(一) —— 读取短信
分类:Android 2012-03-07 12:49 9440人阅读 评论(9) 收藏 举报 sms android integer string date 数据库Android SMS Read
[java] view plain copy print ?
- packagecom.homer.sms;
- importjava.sql.Date;
- importjava.text.SimpleDateFormat;
- importandroid.app.Activity;
- importandroid.database.Cursor;
- importandroid.database.sqlite.SQLiteException;
- importandroid.net.Uri;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.widget.ScrollView;
- importandroid.widget.TableLayout;
- importandroid.widget.TextView;
- /**
- *读取手机短信
- *
- *@authorsunboy_2050
- *@sincehttp://blog.csdn.net/sunboy_2050
- *@date2012.03.06
- */
- publicclasssmsReadextendsActivity{
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- TextViewtv=newTextView(this);
- tv.setText(getSmsInPhone());
- ScrollViewsv=newScrollView(this);
- sv.addView(tv);
- setContentView(sv);
- }
- publicStringgetSmsInPhone(){
- finalStringSMS_URI_ALL="content://sms/";
- finalStringSMS_URI_INBOX="content://sms/inbox";
- finalStringSMS_URI_SEND="content://sms/sent";
- finalStringSMS_URI_DRAFT="content://sms/draft";
- finalStringSMS_URI_OUTBOX="content://sms/outbox";
- finalStringSMS_URI_FAILED="content://sms/failed";
- finalStringSMS_URI_QUEUED="content://sms/queued";
- StringBuildersmsBuilder=newStringBuilder();
- try{
- Uriuri=Uri.parse(SMS_URI_ALL);
- String[]projection=newString[]{"_id","address","person","body","date","type"};
- Cursorcur=getContentResolver().query(uri,projection,null,null,"datedesc");//获取手机内部短信
- if(cur.moveToFirst()){
- intindex_Address=cur.getColumnIndex("address");
- intindex_Person=cur.getColumnIndex("person");
- intindex_Body=cur.getColumnIndex("body");
- intindex_Date=cur.getColumnIndex("date");
- intindex_Type=cur.getColumnIndex("type");
- do{
- StringstrAddress=cur.getString(index_Address);
- intintPerson=cur.getInt(index_Person);
- Stringstrbody=cur.getString(index_Body);
- longlongDate=cur.getLong(index_Date);
- intintType=cur.getInt(index_Type);
- SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");
- Dated=newDate(longDate);
- StringstrDate=dateFormat.format(d);
- StringstrType="";
- if(intType==1){
- strType="接收";
- }elseif(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("noresult!");
- }//endif
- smsBuilder.append("getSmsInPhonehasexecuted!");
- }catch(SQLiteExceptionex){
- Log.d("SQLiteExceptioningetSmsInPhone",ex.getMessage());
- }
- returnsmsBuilder.toString();
- }
- }
AndroidManifest.xml 权限
记得在AndroidManifest.xml中加入android.permission.READ_SMS这个permission
<uses-permissionandroid:name="android.permission.READ_SMS"/>
运行结果:
代码示例
URI主要有:
content://sms/ 所有短信
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿
content://sms/outbox 发件箱
content://sms/failed 发送失败
content://sms/queued 待发送列表
sms主要结构:
- _id => 短消息序号 如100
- thread_id => 对话的序号 如100
- address => 发件人地址,手机号.如+8613811810000
- person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null
- date => 日期long型。如1256539465022
- protocol => 协议0SMS_RPOTO,1MMS_PROTO
- read => 是否阅读0未读,1已读
- status => 状态 -1接收,0complete,64pending,128failed
- type => 类型1是接收到的,2是已发出
- body => 短消息内容
- service_center => 短信服务中心号码编号。如+8613800755500
Cursor cursor = getContentResolver().query(uri, projection, "where .." new String[]{"", ""}, "order by ..")
Android短信存储数据库
偶然发现了Android源码中的一个类MmsSmsDatabaseHelper.java,原来android将所有的短信信息都存入了mmssms.db中。
公开的SDK中没有这个类,不能直接使用。于是自己写了一个SQLiteOpenHelper,但是查询的时候发生SQL异常。看来不能为所欲为了,不过据网上资料介绍可以拷贝db文件来实现短信数据备份。
MmsSmsDatabaseHelper.java在Android源码中的路径:
packages/providers/TelephonyProvider/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
sms数据库中的字段如下:
_id 一个自增字段,从1开始
thread_id 序号,同一发信人的id相同
address 发件人手机号码
person 联系人列表里的序号,陌生人为null
date 发件日期
protocol 协议,分为:0SMS_RPOTO,1MMS_PROTO
read 是否阅读0未读,1已读
status 状态-1接收,0complete,64pending,128failed
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
sms数据库表字段类型的源码:
[java] view plain copy print ?
- privatevoidcreateSmsTables(SQLiteDatabasedb){
- //N.B.:Wheneverthecolumnsherearechanged,thecolumnsin
- //{@refMmsSmsProvider}mustbechangedtomatch.
- db.execSQL("CREATETABLEsms("+
- "_idINTEGERPRIMARYKEY,"+
- "thread_idINTEGER,"+
- "addressTEXT,"+
- "personINTEGER,"+
- "dateINTEGER,"+
- "date_sentINTEGERDEFAULT0,"+
- "protocolINTEGER,"+
- "readINTEGERDEFAULT0,"+
- "statusINTEGERDEFAULT-1,"+//aTP-Statusvalue
- //or-1ifit
- //statushasn't
- //beenreceived
- "typeINTEGER,"+
- "reply_path_presentINTEGER,"+
- "subjectTEXT,"+
- "bodyTEXT,"+
- "service_centerTEXT,"+
- "lockedINTEGERDEFAULT0,"+
- "error_codeINTEGERDEFAULT0,"+
- "seenINTEGERDEFAULT0"+
- ");");
- ....
- }
packages/providers/TelephonyProvider/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
联系人为空
短信数据库里面如果你是先受到陌生短信之后再把陌生人添加到联系人列表的话,短信数据库里面的person字段就为null,如果你是先添加联系人再发短信的话,短信数据库里面的person字段就不为空了,所以你要是想通过短信数据库里的字段取得联系人的其他信息的话,只能通过地址来取。
Android SMS(二)—— 读取短信保存到 SQLite
分类:Android 2012-03-07 13:52 3895人阅读 评论(12) 收藏 举报 sms sqlite android date 数据库 stringAndroid 之 SMS 短信在Android系统中是保存在SQLite数据库中的,但不让其它程序访问(Android系统的安全机制)
现在我们在读取手机内的SMS短信,先保存在我们自己定义的SQLite数据库中,然后读取SQLite数据库提取短信,并显示
SMS短信SQLite存取代码:
[java] view plain copy print ?
- packagecom.homer.sms;
- importjava.sql.Date;
- importjava.text.SimpleDateFormat;
- importorg.loon.wsi.R;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.database.Cursor;
- importandroid.database.sqlite.SQLiteDatabase;
- importandroid.graphics.Color;
- importandroid.net.Uri;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.widget.TableLayout;
- importandroid.widget.TableRow;
- importandroid.widget.TableRow.LayoutParams;
- importandroid.widget.TextView;
- /**
- *读取手机短信,先保存到SQLite数据,然后再读取数据库显示
- *
- *@authorsunboy_2050
- *@sincehttp://blog.csdn.net/sunboy_2050
- *@date2012.03.06
- */
- publicclasssmsRead4extendsActivity{
- TableLayouttableLayout;
- intindex=0;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tableLayout=(TableLayout)findViewById(R.id.tableLayout);
- showSMS();
- }
- privatevoidshowSMS(){
- SmsHandersmsHander=newSmsHander(this);
- smsHander.createSMSDatabase();//创建SQLite数据库
- smsHander.insertSMSToDatabase();//读取手机短信,插入SQLite数据库
- Cursorcursor=smsHander.querySMSInDatabase(100);//获取前100条短信(日期排序)
- cursor.moveToPosition(-1);
- while(cursor.moveToNext()){
- StringstrAddress=cursor.getString(cursor.getColumnIndex("address"));
- StringstrDate=cursor.getString(cursor.getColumnIndex("date"));
- StringstrBody=cursor.getString(cursor.getColumnIndex("body"));
- SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
- Datedate=newDate(Long.parseLong(strDate));
- strDate=dateFormat.format(date);
- StringsmsTitle=strAddress+"\t\t"+strDate;
- StringsmsBody=strBody+"\n";
- Log.i("tableRow",smsTitle+smsBody);
- //titleRow
- TableRowtrTitle=newTableRow(this);
- trTitle.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- TextViewtvTitle=newTextView(this);
- tvTitle.setText(smsTitle);
- tvTitle.getPaint().setFakeBoldText(true);//加粗字体
- tvTitle.setTextColor(Color.RED);
- tvTitle.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- trTitle.addView(tvTitle);
- tableLayout.addView(trTitle,newTableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
- //bodyRow
- TableRowtrBody=newTableRow(this);
- trBody.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- TextViewtvBody=newTextView(this);
- tvBody.setText(smsBody);
- tvBody.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- trBody.addView(tvBody);
- tableLayout.addView(trBody,newTableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
- }
- if(!cursor.isClosed()){
- cursor.close();
- cursor=null;
- }
- smsHander.closeSMSDatabase();
- index=0;
- }
- publicclassSmsHander{
- SQLiteDatabasedb;
- Contextcontext;
- publicSmsHander(Contextcontext){
- this.context=context;
- }
- publicvoidcreateSMSDatabase(){
- Stringsql="createtableifnotexistssms("
- +"_idintegerprimarykeyautoincrement,"
- +"addressvarchar(255),"+"personvarchar(255),"
- +"bodyvarchar(1024),"+"datevarchar(255),"
- +"typeinteger)";
- db=SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString()+"/data.db3",null);//创建数据库
- db.execSQL(sql);
- }
- //获取手机短信
- privateCursorgetSMSInPhone(){
- UriSMS_CONTENT=Uri.parse("content://sms/");
- String[]projection=newString[]{"_id","address","person","body","date","type"};
- Cursorcursor=context.getContentResolver().query(SMS_CONTENT,projection,null,null,"datedesc");//获取手机短信
- while(cursor.moveToNext()){
- System.out.println("--sms--:"+cursor.getString(cursor.getColumnIndex("body")));
- }
- returncursor;
- }
- //保存手机短信到SQLite数据库
- publicvoidinsertSMSToDatabase(){
- LonglastTime;
- CursordbCount=db.rawQuery("selectcount(*)fromsms",null);
- dbCount.moveToFirst();
- if(dbCount.getInt(0)>0){
- Cursordbcur=db.rawQuery("select*fromsmsorderbydatedesclimit1",null);
- dbcur.moveToFirst();
- lastTime=Long.parseLong(dbcur.getString(dbcur.getColumnIndex("date")));
- }else{
- lastTime=newLong(0);
- }
- dbCount.close();
- dbCount=null;
- Cursorcur=getSMSInPhone();//获取短信(游标)
- db.beginTransaction();//开始事务处理
- if(cur.moveToFirst()){
- Stringaddress;
- Stringperson;
- Stringbody;
- Stringdate;
- inttype;
- intiAddress=cur.getColumnIndex("address");
- intiPerson=cur.getColumnIndex("person");
- intiBody=cur.getColumnIndex("body");
- intiDate=cur.getColumnIndex("date");
- intiType=cur.getColumnIndex("type");
- do{
- address=cur.getString(iAddress);
- person=cur.getString(iPerson);
- body=cur.getString(iBody);
- date=cur.getString(iDate);
- type=cur.getInt(iType);
- if(Long.parseLong(date)>lastTime){
- Stringsql="insertintosmsvalues(null,?,?,?,?,?)";
- Object[]bindArgs=newObject[]{address,person,body,date,type};
- db.execSQL(sql,bindArgs);
- }else{
- break;
- }
- }while(cur.moveToNext());
- cur.close();
- cur=null;
- db.setTransactionSuccessful();//设置事务处理成功,不设置会自动回滚不提交
- db.endTransaction();//结束事务处理
- }
- }
- //获取SQLite数据库中的全部短信
- publicCursorquerySMSFromDatabase(){
- Stringsql="select*fromsmsorderbydatedesc";
- returndb.rawQuery(sql,null);
- }
- //获取SQLite数据库中的最新size条短信
- publicCursorquerySMSInDatabase(intsize){
- Stringsql;
- CursordbCount=db.rawQuery("selectcount(*)fromsms",null);
- dbCount.moveToFirst();
- if(size<dbCount.getInt(0)){//不足size条短信,则取前size条
- sql="select*fromsmsorderbydatedesclimit"+size;
- }else{
- sql="select*fromsmsorderbydatedesc";
- }
- dbCount.close();
- dbCount=null;
- returndb.rawQuery(sql,null);
- }
- //获取SQLite数据库的前second秒短信
- publicCursorgetSMSInDatabaseFrom(longsecond){
- longtime=System.currentTimeMillis()/1000-second;
- Stringsql="select*fromsmsorderbydatedescwheredate>"+time;
- returndb.rawQuery(sql,null);
- }
- //关闭数据库
- publicvoidcloseSMSDatabase(){
- if(db!=null&&db.isOpen()){
- db.close();
- db=null;
- }
- }
- }
- }
代码示例
推荐参考:
Android 之 SMS 短信读取
更多相关文章
- android最简单的发送文本短信的demo
- android 拨打电话与发送短信
- Android中短信拦截的实现
- 关于 SQLiteOpenHelper 的自创建数据库目录文件
- Android 拦截 接收 短信
- android 读取短信内容
- Android 数据库事务操作