java中回掉函数可以看作观察者模式的一种较为简单的具体实现。
package com.itheima.mobilesafe74.engine;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xmlpull.v1.XmlSerializer;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Xml;
public class SmsBackUp {
/**
* 备份短信到指定的xml文件中
*
* @param context
* @param progressDialog
* 带有进度条的对话框,以便将短信备份的过程用进度条显示
*/
public static void BackUpSms(Context context, CallBack callBack){
/**
* 1.得到短信 2.序列化到xml中 3.更新到进度条上面
*/
FileOutputStream fileOutputStream = null;
// 得到短信集合cursor
Uri path = Uri.parse("content://sms");
Cursor cursor = context.getContentResolver().query(path,
new String[] { "address", "date", "type", "body" }, null, null,
null);
String smsXmlPath = context.getFilesDir().getAbsolutePath();
File file = new File(smsXmlPath, "smss.xml");
try {
fileOutputStream = new FileOutputStream(file);
// 序列化xml文件
XmlSerializer xmlSerializer = Xml.newSerializer();
xmlSerializer.setOutput(fileOutputStream, "utf-8");// 注明xml文件导出的路径和编码
xmlSerializer.startDocument("utf-8", true);
xmlSerializer.startTag(null, "smss");// 开始标签
// 短信的条数
int count = cursor.getCount();
// 已经备份的短信的条数
int hasBackupCount = 0;
// 设置progressDialog总进度条的总数
if (callBack!=null) {
callBack.setMax(count);
}
while (cursor.moveToNext()) {
xmlSerializer.startTag(null, "sms");
String address = cursor.getString(0);
String date = cursor.getString(1);
String type = cursor.getString(2);
String body = cursor.getString(3);
xmlSerializer.attribute(null, "address", address);
xmlSerializer.startTag(null, "date");
xmlSerializer.text(date);
xmlSerializer.endTag(null, "date");
xmlSerializer.startTag(null, "type");
xmlSerializer.text(type);
xmlSerializer.endTag(null, "type");
xmlSerializer.startTag(null, "body");
xmlSerializer.text(body);
xmlSerializer.endTag(null, "body");
xmlSerializer.endTag(null, "sms");
hasBackupCount++;
SystemClock.sleep(100);
if (callBack!=null) {
callBack.setProgress(hasBackupCount);
}
}
xmlSerializer.endTag(null, "smss");
xmlSerializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (cursor!=null&&fileOutputStream!=null) {
cursor.close();
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 回掉函数接口,用来适应传递进来不同的控件
* 不论外面想传递什么控件进来,都需要实现callBack接口,实现了接口,就需要实现相应的方法
* @author 编程只服JAVA
*
*/
public interface CallBack{
public void setMax(int max);
public void setProgress(int progress);
}
}