Android实现支持进度条显示的短信备份工具类
使用内容提供者读取短信内容,写入XML文件,进度条ProgressDialog更新备份进度。
新知识点:子线程如何在在不使用Handler的情况下更新UI
/** *进行短信备份的工具类,支持进度条显示 *@authorlian * */ publicclassSmsBackupUtils{ privatestaticclassData{ intprogress; } /** * *@paramcontext *调用此工具类的Activity *@parampd *显示备份进度的进度条 */ publicstaticvoidsmsBackup(Activitycontext,finalProgressDialogpd){ Uriuri=Uri.parse("content://sms/"); ContentResolvercr=context.getContentResolver(); //取出短信 finalCursorcursor=cr.query(uri,newString[]{"address","date","body","type"},null,null,null); finalintcount=cursor.getCount(); finalDatadata=newData(); data.progress=0; //存储路径 Filefile=newFile(Environment.getExternalStorageDirectory(),"sms.xml"); try{ FileOutputStreamfos=newFileOutputStream(file); PrintWriterpw=newPrintWriter(fos); //按照XML格式进行写入 pw.println("<smsescount='"+cursor.getCount()+"'>"); //在主线程中更新UI context.runOnUiThread(newRunnable(){ @Override publicvoidrun(){ //TODOAuto-generatedmethodstub pd.setMax(count); pd.show(); } }); //写入XML文件 while(cursor.moveToNext()){ data.progress++; Stringaddress=cursor.getString(0); Stringdate=cursor.getString(1); Stringbody=cursor.getString(2); Stringtype=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(newRunnable(){ @Override publicvoidrun(){ //TODOAuto-generatedmethodstub pd.setProgress(data.progress); } }); } pw.println("</smses>"); pw.flush(); pw.close(); cursor.close(); //备份完成,关闭进度条 context.runOnUiThread(newRunnable(){ @Override publicvoidrun(){ //TODOAuto-generatedmethodstub pd.dismiss(); } }); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }
调用
pd=newProgressDialog(this); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); SmsBackupUtils.smsBackup(SuperToolActivity.this,pd);
以上就是本文的全部内容,希望对大家的学习有所帮助。