首页 > 系统 > Android > 正文

Android实现支持进度条显示的短信备份工具类

2020-01-02 06:59:26
字体:
来源:转载
供稿:网友

使用内容提供者读取短信内容,写入XML文件,进度条ProgressDialog更新备份进度。
新知识点:子线程如何在在不使用Handler的情况下更新UI

/**  *   进行短信备份的工具类,支持进度条显示  * @author lian  *  */  public class SmsBackupUtils {   private static class Data{     int progress;   }      /**    *    * @param context    *   调用此工具类的Activity    * @param pd    *   显示备份进度的进度条    */   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); 

以上就是本文的全部内容,希望对大家的学习有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表