使用ddms给模拟器发送几条短信,找到短信数据库导出
/data/data/com.android.providers.telephony/databases/mmssms.db
数据库字段:address(手机号),date(日期),type(1接收,2发送),body(内容)
在系统的全部源代码中找到packages/providers/TelephonyProvider
查看清单文件,找到provider节点,
看到android:readPermisssion=”android.permission.READ_SMS”
android:writePermission=”android.permission.WRITE_SMS” 权限
找到TelephonyProvider类里的satic静态代码块,看到规则部分,最简单的content://sms/
调用Uri类的parse(string) 方法,获取到Uri对象
调用getContentResolver()方法,获取ContentResolver对象,中间人对象
调用ContentResolver对象的query(uri,projection,selection,selectArgs,sortOrder)方法,得到Cursor对象,参数:projection是String[] 查询字段,条件,参数,排序
while循环Cursor对象,调用Cursor对象的moveToNext() ,调用Cursor对象的getString(),调用Cursor对象的getClumnIndex()
数据中日期date字段是时间戳毫秒值
在清单文件中定义一下权限
当短信内容比较少的时候没问题,多的时候会有问题,应该是遍读遍备份。
根据xml文件的序列化那节,完成保存到文件中。保存到sd卡的时候也要权限
activity:
package com.tsh.backsmstrue; import java.util.ArrayList; java.util.List; com.tsh.backsmstrue.domain.SmsInfo; com.tsh.backsmstrue.utils.SmsUtil; android.app.Activity; android.content.ContentResolver; android.database.Cursor; android.net.Uri; android.os.Bundle; android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * 备份短信 * @param v */ backupSms(View v){ Uri uri=Uri.parse("content://sms/"); ContentResolver resolver=getContentResolver(); String[] projection=new String[]{"address","date","type","body"}; Cursor cursor=resolver.query(uri,null,1)">null); List<SmsInfo> smss=new ArrayList<SmsInfo>(); while(cursor.moveToNext()){ String body=cursor.getString(cursor.getColumnIndex("body")); System.out.println(body); System.out.println("==========="); SmsInfo smsinfo=new SmsInfo(); smsinfo.setAddress("110"); smsinfo.setMessage(body); smss.add(smsinfo); } SmsUtil.backSms2(smss,this); cursor.close(); } }
工具类:
com.tsh.backsmstrue.utils; java.io.File; java.io.FileOutputStream; org.xmlpull.v1.XmlSerializer; com.tsh.backsmstrue.domain.SmsInfo; android.content.Context; android.os.Environment; android.util.Xml; android.view.View; android.widget.Toast; class SmsUtil { * 备份短信第二种 * static void backSms2(List<SmsInfo> smsInfos,Context context){ XmlSerializer serializer=Xml.newSerializer(); try { File file=new File(Environment.getExternalStorageDirectory(),"backup2.xml"); FileOutputStream os= FileOutputStream(file); serializer.setOutput(os,"utf-8"); serializer.startDocument("utf-8",1)">true); serializer.startTag(); for(SmsInfo sms:smsInfos){ serializer.startTag(); serializer.attribute(,sms.getAddress()); serializer.text(sms.getMessage()); serializer.endTag(); } serializer.endTag(); serializer.endDocument(); os.close(); Toast.makeText(context,"保存成功",0).show(); } catch (Exception e) { Toast.makeText(context,"保存失败",1)">).show(); } } }