package indi.cc.createxml
import indi.cc.createxml.domain.Message
import java.io.File
import java.io.FileOutputStream
import java.util.ArrayList
import java.util.List
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.ActionBarActivity
import android.view.View
public class MainActivity extends ActionBarActivity {
List<Message> smsList
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//虚拟10条短信
smsList = new ArrayList<Message>()
for(int i = 0
Message sms = new Message("哈哈哈哈哈哈哈" + i, System.currentTimeMillis() + "", "138"+i+i, "1")
smsList.add(sms)
}
}
public void click(View v){
//在内存中把xml备份短信的格式拼接出来
StringBuffer sb = new StringBuffer()
sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>")
sb.append("<messages>")
for (Message sms : smsList) {
sb.append("<sms>")
sb.append("<body>")
sb.append(sms.getBody())
sb.append("</body>")
sb.append("<date>")
sb.append(sms.getDate())
sb.append("</date>")
sb.append("<type>")
sb.append(sms.getType())
sb.append("</type>")
sb.append("<address>")
sb.append(sms.getAddress())
sb.append("</address>")
sb.append("</sms>")
}
sb.append("</messages>")
//File file = new File("sdcard/sms.xml")
File file = new File(Environment.getExternalStorageDirectory().getPath(),"sms.xml")
try {
FileOutputStream fos = new FileOutputStream(file)
fos.write(sb.toString().getBytes())
fos.close()
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
package indi.cc.createxml.domain;
public class Message {
private String body;
private String date;
private String address;
private String type;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Message(String body, String date, String address, String type) {
super();
this.body = body;
this.date = date;
this.address = address;
this.type = type;
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="indi.cc.createxml.MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="备份短信"
android:onClick="click"
/>
</RelativeLayout>