短信备份的原理
短信备份的原理,是用内容提供者读取短信,然后保存。
public class SmsBackupUtils { // 回调接口 public interface SmsBackupCallback { /** * 短信备份前调用 * @param total 短信的总条数 */ public void beforeSmsbackup(int total); /** * 短信调用中调用 * @param progress 短信的进度 */ public void progressSmsbackup(int progress); } /** * 短信备份的方法,备份到xml文件中,因为xml文件跨平台性强 这是一个耗时操作,应该放在子线程中执行 * * @param context 上下文 * @param path 备份到哪个路径 * @throws Exception */ public static void smsBackup(Context context, String path,SmsBackupCallback callBack) throws Exception { // xml的序列化器 XmlSerializer serializer = Xml.newSerializer(); File file = new File(path); FileOutputStream fos = new FileOutputStream(file); // 设置参数 serializer.setOutput(fos, "utf-8"); // 开始 serializer.startDocument("utf-8", true); serializer.startTag(null, "smss"); ContentResolver resolver = context.getContentResolver(); Uri uri = Uri.parse("content://sms");// 包含所有短信 Cursor cursor = resolver.query(uri, new String[] { "address", "date", "type", "body" }, null, null, null); /*dialog.setMax(cursor.getCount()); progressBar1.setMax(cursor.getCount());*/ callBack.beforeSmsbackup(cursor.getCount()); int progress = 0; while (cursor.moveToNext()) { serializer.startTag(null, "sms"); serializer.startTag(null, "address"); String address = cursor.getString(0); serializer.text(address); serializer.endTag(null, "address"); serializer.startTag(null, "date"); String date = cursor.getString(1); serializer.text(date); serializer.endTag(null, "date"); serializer.startTag(null, "type"); String type = cursor.getString(2); serializer.text(type); serializer.endTag(null, "type"); serializer.startTag(null, "body"); String body = cursor.getString(3); serializer.text(body); serializer.endTag(null, "body"); serializer.endTag(null, "sms"); progress++; /*dialog.setProgress(progress); progressBar1.setProgress(progress);*/ callBack.progressSmsbackup(progress); SystemClock.sleep(1000); } cursor.close(); serializer.endTag(null, "smss"); serializer.endDocument(); } }
原文:http://blog.csdn.net/chengjun77/article/details/38934007