因为短信的内容已经通过ContentProvider暴露出来,所以我们可以直接用内容解析者获取短信内容。
想要获取短信内容,你需要知道的一些东西:
1、Uri uri = Uri.parse("content://sms/");
2、Cursor cursor = getContentResolver().query(uri,new String[]{"address","date","body"},null,null,null);
知道了这个就好获取短信的相关信息了
先看代码吧:
public void onClick(View v) { XmlSerializer serializer = Xml.newSerializer(); File file = new File(Environment.getExternalStorageDirectory().getPath(),"smsbackup.xml"); try { FileOutputStream outputStream = new FileOutputStream(file); serializer.setOutput(outputStream, "utf-8"); serializer.startDocument("utf-8",true); serializer.startTag(null,"smss"); Uri uri = Uri.parse("content://sms/"); Cursor cursor = getContentResolver().query(uri,new String[]{"address","date","body"},null,null,null); if (cursor!=null){ while (cursor.moveToNext()){ String address = cursor.getString(0); String date = cursor.getString(1); String body = cursor.getString(2); try { //sms节点 serializer.startTag(null,"sms"); //address节点 serializer.startTag(null,"address"); serializer.text(address); serializer.endTag(null,"address"); //date节点 serializer.startTag(null,"date"); serializer.text(date); serializer.endTag(null,"date"); //body节点 serializer.startTag(null,"body"); serializer.text(body); serializer.endTag(null,"body"); serializer.endTag(null,"sms"); } catch (IOException e) { e.printStackTrace(); } System.out.println(address+"---"+date+"---"+body); } } serializer.endTag(null,"smss"); serializer.endDocument(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
主要用内容解析者获取短信的信息和内容,然后用XmlSerializer存储。
下面是Manifest.xml:需要加上这三个权限
<uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.WRITE_SMS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>