SoFunction
Updated on 2025-03-11

Android implements SMS backup tool class that supports progress bar display

Use the content provider to read the text message content, write to the XML file, and update the backup progress.

New knowledge points:How do child threads update UI without using Handler

/**
  * Tool class for SMS backup, support progress bar display
  * @author lian
  *
  */ 
 
public class SmsBackupUtils { 
  private static class Data{ 
    int progress; 
  } 
   
  /**
    *
    * @param context
    * Call the activity of this tool class
    * @param pd
    * The progress bar displays the backup progress
    */ 
  public static void smsBackup(Activity context,final ProgressDialog pd){ 
    Uri uri = ("content://sms/"); 
    ContentResolver cr = (); 
     
    //Check out the text message    final Cursor cursor = (uri, new String[]{"address","date","body","type"}, null, null, null); 
     
    final int count = (); 
     
    final Data data = new Data(); 
     = 0; 
     
    //Storage path    File file = new File((), ""); 
    try { 
      FileOutputStream fos = new FileOutputStream(file); 
      PrintWriter pw = new PrintWriter(fos); 
       
      //Write in XML format      ("<smses count='" + () +"'>"); 
       
      //Update the UI in the main thread      (new Runnable() { 
         
        @Override 
        public void run() { 
          // TODO Auto-generated method stub 
          (count); 
          (); 
        } 
      }); 
       
      //Write to XML file      while(()){ 
         ++; 
        String address = (0); 
        String date = (1); 
        String body = (2); 
        String type = (3); 
         
        //(150); 
        ("<sms>"); 
        ("<address>"+ address +"</address>"); 
        ("<date>"+ date +"</date>"); 
        ("<body>"+ body +"</body>"); 
        ("<type>"+ type +"</type>"); 
        ("</sms>"); 
         
        (new Runnable() { 
           
          @Override 
          public void run() { 
            // TODO Auto-generated method stub 
            (); 
          } 
        }); 
         
      } 
      ("</smses>"); 
      (); 
      (); 
      (); 
      //Backup is completed, close the progress bar      (new Runnable() { 
        @Override 
        public void run() { 
          // TODO Auto-generated method stub 
          (); 
        } 
      }); 
    } catch (Exception e) { 
      // TODO Auto-generated catch block 
      (); 
    } 
     
     
  } 
} 

Call

pd = new ProgressDialog(this); 
(ProgressDialog.STYLE_HORIZONTAL); 
 
(, pd); 

The above is all about this article, I hope it will be helpful to everyone's learning.