1 package com.lidaochen.phonecall; 2 3 import android.net.Uri; 4 import android.os.Environment; 5 import android.support.v7.app.AppCompatActivity; 6 import android.os.Bundle; 7 import android.util.Log; 8 import android.util.Xml; 9 import android.view.View; 10 import android.widget.Button; 11 import android.widget.TabHost; 12 import android.widget.ThemedSpinnerAdapter; 13 import android.widget.Toast; 14 15 import org.xmlpull.v1.XmlSerializer; 16 17 import java.io.File; 18 import java.io.FileOutputStream; 19 import java.util.ArrayList; 20 import java.util.List; 21 22 public class MainActivity extends AppCompatActivity{ 23 private List<Sms> smsLists; 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 // 初始化我们要备份的数据 29 smsLists = new ArrayList<Sms>(); 30 for (int i = 0; i < 10; i++) 31 { 32 Sms sms = new Sms(); 33 sms.setAddres("10000" + i); 34 sms.setBody("Hello" + i); 35 sms.setDate("500" + i); 36 // 把sms对象加入到集合中 37 smsLists.add(sms); 38 } 39 } 40 // 按钮点击事件 41 public void click(View v) 42 { 43 try{ 44 // 1、通过Xml这个工具类去获取XmlSerializer类的实例 45 XmlSerializer serializer = Xml.newSerializer(); 46 // 2、设置XmlSerializer序列化器参数 47 File file = new File(Environment.getExternalStorageDirectory().getPath(), "LiDaochen.xml"); 48 FileOutputStream fos = new FileOutputStream(file); 49 serializer.setOutput(fos, "utf-8"); 50 // 3、写xml文档开头 51 serializer.startDocument("utf-8", true); 52 // 4、写xml根节点 53 serializer.startTag(null, "smss"); 54 for(Sms sms:smsLists) 55 { 56 serializer.startTag(null, "sms"); 57 // address节点 58 serializer.startTag(null, "addres"); 59 serializer.text(sms.getAddres()); 60 serializer.endTag(null, "addres"); 61 // body节点 62 serializer.startTag(null, "body"); 63 serializer.text(sms.getBody()); 64 serializer.endTag(null, "body"); 65 // date节点 66 serializer.startTag(null, "date"); 67 serializer.text(sms.getDate()); 68 serializer.endTag(null, "date"); 69 serializer.endTag(null, "sms"); 70 } 71 // 文档结尾 72 serializer.endTag(null, "smss"); 73 serializer.endDocument(); 74 // 关闭流 75 fos.close(); 76 } 77 catch (Exception e) 78 { 79 e.printStackTrace(); 80 } 81 } 82 }
1 package com.lidaochen.phonecall; 2 3 public class Sms { 4 private String addres; 5 private String body; 6 private String date; 7 8 public String getAddres() { 9 return addres; 10 } 11 12 public String getBody() { 13 return body; 14 } 15 16 public String getDate() { 17 return date; 18 } 19 20 public void setAddres(String addres) { 21 this.addres = addres; 22 } 23 24 public void setBody(String body) { 25 this.body = body; 26 } 27 28 public void setDate(String date) { 29 this.date = date; 30 } 31 }