首页 > 代码库 > ContentProvider备份短信,以xml文件存储

ContentProvider备份短信,以xml文件存储

因为短信的内容已经通过ContentProvider暴露出来,所以我们可以直接用内容解析者获取短信内容。

想要获取短信内容,你需要知道的一些东西:

1、Uri uri = Uri.parse("content://sms/");

2、Cursor cursor = getContentResolver().query(uri,new String[]{"address","date","body"},null,null,null);

 

知道了这个就好获取短信的相关信息了

先看代码吧:

 

 1 public void onClick(View v) {
 2         XmlSerializer serializer = Xml.newSerializer();
 3         File file = new File(Environment.getExternalStorageDirectory().getPath(),"smsbackup.xml");
 4         try {
 5             FileOutputStream outputStream =   new FileOutputStream(file);
 6             serializer.setOutput(outputStream, "utf-8");
 7             serializer.startDocument("utf-8",true);
 8             serializer.startTag(null,"smss");
 9 
10             Uri uri = Uri.parse("content://sms/");
11             Cursor cursor = getContentResolver().query(uri,new String[]{"address","date","body"},null,null,null);
12             if (cursor!=null){
13             while (cursor.moveToNext()){
14                 String address = cursor.getString(0);
15                 String date = cursor.getString(1);
16                 String body = cursor.getString(2);
17 
18                 try {
19                     //sms节点
20                     serializer.startTag(null,"sms");
21                     //address节点
22                     serializer.startTag(null,"address");
23                     serializer.text(address);
24                     serializer.endTag(null,"address");
25                     //date节点
26                     serializer.startTag(null,"date");
27                     serializer.text(date);
28                     serializer.endTag(null,"date");
29                     //body节点
30                     serializer.startTag(null,"body");
31                     serializer.text(body);
32                     serializer.endTag(null,"body");
33 
34                     serializer.endTag(null,"sms");
35 
36                 } catch (IOException e) {
37                     e.printStackTrace();
38                 }
39                 System.out.println(address+"---"+date+"---"+body);
40             }
41         }
42             serializer.endTag(null,"smss");
43             serializer.endDocument();
44             outputStream.close();
45         } catch (FileNotFoundException e) {
46             e.printStackTrace();
47         } catch (IOException e) {
48             e.printStackTrace();
49         }
50 
51     }

 

主要用内容解析者获取短信的信息和内容,然后用XmlSerializer存储。

下面是Manifest.xml:需要加上这三个权限

1     <uses-permission android:name="android.permission.READ_SMS"/>
2     <uses-permission android:name="android.permission.WRITE_SMS"/>
3     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

ContentProvider备份短信,以xml文件存储