Android进行短信备份的一个工具类,支持进度条显示

使用内容提供者读取短信内容,写入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);


你可能感兴趣的:(android,新手,ProgressDialog,短信备份,子线程更新Ui)