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

时间:2022-09-20 14:59:15

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
 *   进行短信备份的工具类,支持进度条显示
 * @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();
    }
     
     
  }
}

调用

?
1
2
3
4
pd = new progressdialog(this);
pd.setprogressstyle(progressdialog.style_horizontal);
 
smsbackuputils.smsbackup(supertoolactivity.this, pd);

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