通过点击button来备份短信 索性直接写成工具类得了
①第一点 初始化布局 Initview(context);
private static void Initview(Context context) {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在备份数据");
pd.show();
}
②得到一个SD卡路径进行读取,因为要按照一定的格式写入,所以使用XML 注意加权限
File file = new File(Environment.getExternalStorageDirectory(),
"backup.xml");
FileOutputStream fos = new FileOutputStream(file);
③ 通过内容提供者得到 短信的发件人 内容 类型 ,日期
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://sms/");
Cursor cursor = resolver.query(uri, new String[] { "body", "address",
"type", "date" }, null, null, null);
④通过pull解析组装xml 输出到SD卡中
XmlSerializer serializer = Xml.newSerializer();
// 初始化生成器
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "smss");
serializer.attribute(null, "max", max + "");
int process = 0;
while (cursor.moveToNext()) {
Thread.sleep(500);
String body = cursor.getString(0);
String address = cursor.getString(1);
String type = cursor.getString(2);
String date = cursor.getString(3);
serializer.startTag(null, "sms");
serializer.startTag(null, "body");
serializer.text(body);
serializer.endTag(null, "body");
serializer.startTag(null, "address");
serializer.text(address);
serializer.endTag(null, "address");
serializer.startTag(null, "type");
serializer.text(type);
serializer.endTag(null, "type");
serializer.startTag(null, "date");
serializer.text(date);
serializer.endTag(null, "date");
serializer.endTag(null, "sms");
// 备份过程中,增加进度
process++;
// pb.setProgress(process);
pd.setProgress(process);
}
cursor.close();
serializer.endTag(null, "smss");
serializer.endDocument();
fos.close();
// pd.dismiss();
}
在 activity中掉用 也简单
@Override
public void onClick(View v) {
try {
SmsUtils.backupSms(this);
Toast.makeText(SmsActivity.this, "备份成功", Toast.LENGTH_SHORT);
} catch (Exception e) {
Toast.makeText(SmsActivity.this, "备份失败", Toast.LENGTH_SHORT);
e.printStackTrace();
}
}
这一节不是很好,有点小bug,在下一节 我将用接口回调解耦