使用内容提供者读取短信内容,写入XML文件,进度条ProgressDialog更新备份进度。
新知识点:子线程如何在在不使用Handler的情况下更新UI
public class SmsBackupUtils {
private static class Data{
int progress;
}
public static void smsBackup(Activity context,final ProgressDialog pd){
Uri uri = Uri.parse("content://sms/");
ContentResolver cr = context.getContentResolver();
//取出短信
final Cursor cursor = cr.query(uri, new String[]{"address","date","body","type"}, null, null, null);
final int count = cursor.getCount();
final Data data = new Data();
data.progress = 0;
//存储路径
File file = new File(Environment.getExternalStorageDirectory(), "sms.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
//按照XML格式进行写入
pw.println("<smses count='" + cursor.getCount() +"'>");
//在主线程中更新UI
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.setMax(count);
pd.show();
}
});
//写入XML文件
while(cursor.moveToNext()){
data.progress ++;
String address = cursor.getString(0);
String date = cursor.getString(1);
String body = cursor.getString(2);
String type = cursor.getString(3);
//SystemClock.sleep(150);
pw.println("<sms>");
pw.println("<address>"+ address +"</address>");
pw.println("<date>"+ date +"</date>");
pw.println("<body>"+ body +"</body>");
pw.println("<type>"+ type +"</type>");
pw.println("</sms>");
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.setProgress(data.progress);
}
});
}
pw.println("</smses>");
pw.flush();
pw.close();
cursor.close();
//备份完成,关闭进度条
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
调用
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
SmsBackupUtils.smsBackup(SuperToolActivity.this, pd);
您可能感兴趣的文章:Android接收和发送短信的实现代码Android使用MobSDK短信验证Android实现短信验证码获取自动填写功能(详细版)Android实现短信验证码自动拦截读取功能Android开发工程中集成mob短信验证码功能的方法Android手机号注册、绑定手机号获取短信验证码实例Android获取和读取短信验证码的实现方法Android如何通过手机自动获取短信验证码android教程之intent的action属性使用示例(intent发短信)Android实战教程第九篇之短信高效备份