Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47091281
At present, some software in Android phone can realize the backup and restore operation of SMS. This blog post is to show you how to implement the backup and restore operation of Android SMS. Well, I believe that you are more interested in these practical functions, not much to say, we directly into the subject bar.
First, the principle
My implementation principle is very simple, the interface placed several TextView list, two of which are "SMS Backup" and "text message Restore", click "SMS Backup", read all the text messages, the text message is saved in an XML file, the XML file placed in the SDcard, As a backup file for text messages, and then when you need to restore text messages, just click "Restore text Messages", then the program will first delete the existing text messages on the phone, and then from the text message backup XML file to read the previous backup of the text message, written to the SMS database.
The principle is finished, is it very simple? Next, let's implement these features together!
Second, Practice 1, create a text message entity class Smsinfo
In order to make the program more object-oriented, more in line with object-oriented encapsulation, I encapsulated the message information into an entity class Smsinfo
The specific code is as follows:
Package cn.lyz.mobilesafe.domain;/** * SMS Content entity class * @author Liuyazhuang * */public class Smsinfo {//Phone number private String Addre ss;//Date private string date;//SMS type private string type;//SMS content private string Body;public Smsinfo () {super ();//TODO Auto-generated constructor Stub}public Smsinfo (string address, string date, String type, string body) {super (); This.addre SS = Address;this.date = Date;this.type = Type;this.body = Body;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} Public String GetDate () {return date;} public void SetDate (String date) {this.date = date;} Public String GetType () {return type;} public void SetType (String type) {this.type = type;} Public String GetBody () {return body;} public void Setbody (String body) {this.body = body;} @Overridepublic String toString () {return "Smsinfo [address=" + Address + ", date=" + Date + ", type=" + Type + ", body=" + Body + "]";}}
2. Create SMS Operation Business Class Smsinfoservice
This class mainly encapsulates the operation of the SMS data, and encapsulates the writing and parsing operations of the XML file. The backup SMS process is to first read the text message from the SMS database and then write the text message to the XML file. The process of restoring a text message is to delete the SMS from the phone, then parse the backup SMS file and write the text message to the SMS database.
The specific implementation code is as follows:
Package Cn.lyz.mobilesafe.engine;import Java.io.file;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.io.outputstream;import Java.util.ArrayList;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.xmlserializer;import Android.content.context;import Android.database.cursor;import Android.net.uri;import android.os.Environment; Import Android.util.xml;import cn.lyz.mobilesafe.domain.smsinfo;/** * Business class to get SMS content * @author Liuyazhuang * */public class S Msinfoservice {private Context context;public Smsinfoservice (Context context) {//TODO auto-generated constructor Stubthis.context = context;} Get all SMS Public list<smsinfo> Getsmsinfos () {list<smsinfo> Smsinfos = new arraylist<smsinfo> (); Uri uri = uri.parse ("content://sms"); Cursor C = context.getcontentresolver (). Query (URI, new string[]{"Address", "date", "type", "body"}, NULL, NULL, NULL); while (C.movetonext ()) {String address = c.getstring (C.getcolumnindeX ("Address")); String date = c.getstring (C.getcolumnindex ("date")); String type = c.getstring (C.getcolumnindex ("type")); String BODY = c.getstring (C.getcolumnindex ("body")); Smsinfo smsinfo = new Smsinfo (address, date, type, body); Smsinfos.add (smsinfo);} return Smsinfos;} Write SMS data to XML file public void Createxml (List<smsinfo> smsinfos) throws Exception{xmlserializer serializer = Xml.newserializer (); File File = new file (Environment.getexternalstoragedirectory (), "Smsbackup.xml"), OutputStream OS = new FileOutputStream (file); Serializer.setoutput (OS, "UTF-8"); Serializer.startdocument ("UTF-8", true); Serializer.starttag (null, " Smsinfos "); for (Smsinfo Info:smsinfos) {Serializer.starttag (null," Smsinfo ");//addressserializer.starttag (null," Address "), Serializer.text (Info.getaddress ()), Serializer.endtag (NULL," address "),//dateserializer.starttag (NULL, "Date"), Serializer.text (Info.getdate ()), Serializer.endtag (null, "date"),//typeserializer.starttag (null, "type"); Serializer.text (Info.gettype ()); SerializEr.endtag (NULL, "type");//bodyserializer.starttag (null, "body"); Serializer.text (Info.getbody ()); Serializer.endtag (NULL, "body"); Serializer.endtag (null, "Smsinfo");} Serializer.endtag (NULL, "Smsinfos"); Serializer.enddocument (); Os.close ();} Get SMS data from XML file public list<smsinfo> Getsmsinfosfromxml () throws exception{list<smsinfo> Smsinfos =null; Smsinfo smsinfo = null; Xmlpullparser parser = Xml.newpullparser (); File File = new file (Environment.getexternalstoragedirectory (), "Smsbackup.xml"); InputStream InputStream = new FileInputStream (file);p arser.setinput (InputStream, "UTF-8"); int eventtype = Parser.geteventtype (); while (EventType!) = xmlpullparser.end_document) {switch (eventtype) {case XmlPullParser.START_TAG:if ("Smsinfos". Equals (Parser.getname ()) {Smsinfos = new arraylist<smsinfo> ();} else if ("Smsinfo". Equals (Parser.getname ())) {smsinfo = new Smsinfo ();} else if ("Address". Equals (Parser.getname ())) {String address = Parser.nexttext (); smsinfo.setaddress (address);} else if ("date". EQUals (Parser.getname ())) {String date = Parser.nexttext (); smsinfo.setdate (date);} else if ("type". Equals (Parser.getname ())) {String type = Parser.nexttext (); Smsinfo.settype (type);} else if ("Body". Equals (Parser.getname ())) {String BODY = Parser.nexttext (); Smsinfo.setbody (body);} Break;case XmlPullParser.END_TAG:if ("Smsinfo". Equals (Parser.getname ())) {Smsinfos.add (smsinfo); smsinfo = Nu ll;} Break;default:break;} EventType = Parser.next ();} return Smsinfos;}}
3, create a backup SMS service class Backupsmsservice
This class is mainly to implement the operation of backup SMS, the operation of the backup SMS is placed in a service class to execute, because the operation of the read database is a time-consuming operation, so I opened a thread in this class to do the backup operation of SMS, if the backup SMS fails, the user is prompted to backup failure, if the backup SMS is successful, Notify the user that the SMS backup was successful. Stop the service after the operation is complete.
The specific implementation code is as follows:
Package Cn.lyz.mobilesafe.service;import Java.util.list;import Android.app.notification;import Android.app.notificationmanager;import Android.app.pendingintent;import Android.app.service;import Android.content.context;import Android.content.intent;import Android.os.ibinder;import Android.os.Looper;import Android.widget.toast;import Cn.lyz.mobilesafe.r;import Cn.lyz.mobilesafe.activity.mainactivity;import Cn.lyz.mobilesafe.domain.smsinfo;import cn.lyz.mobilesafe.engine.smsinfoservice;/** * Service class for Backup SMS * @author Liuyazhuang * */public class Backupsmsservice extends Service {private smsinfoservice smsinfoservice;private notificationmanager nm; @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); smsinfoservice = new Smsinfoservice ( This), NM = (Notificationmanager) getsystemservice (context.notification_service); new Thread () {public void run () {//1 Get all the SMS//2 generate an XML file list<smsinfo> Smsinfos = Smsinfoservice.getsmsinfos (); try {smsinfoservice.createxml ( Smsinfos);//Send a notification informing the user that the backup completed notification notification = new notification (r.drawable.notification, "SMS Backup Complete", System.currenttimemillis ()); Intent Intent = new Intent (Getapplicationcontext (), mainactivity.class); Pendingintent contentintent = pendingintent.getactivity (Getapplicationcontext (), N, intent, 0); Notification.setlatesteventinfo (Getapplicationcontext (), "Prompt message", "SMS Backup Complete", contentintent);// Click the notification message to disappear automatically notification.flags = notification.flag_auto_cancel;nm.notify (Notification);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();//looper is a message pump that extracts messages from the message queue (MessageQueue). Give the message to handler to handle looper.prepare (); Toast.maketext (Getapplicationcontext (), "SMS Backup Failed", 0). Show (); Looper.loop ();} Stopself ();//Stop Service};}. Start ();} @Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;}}
4. Layout implementation
The specific implementation code is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <textview style= "@style/text_title_style" android:text= "Advanced Tools"/> <view style= " @style/view_divide_line_style "/> <textview android:id=" @+id/tv_atools_add_ipcall "Android:layout_w Idth= "Match_parent" android:layout_height= "Wrap_content" android:text= "Add IP Dial" android:textcolor= "@android: color/ White "android:textsize=" 20sp "android:paddingtop=" 10DP "android:paddingbottom=" 10DP "/> <include Lay out= "@layout/line"/> <textview android:id= "@+id/tv_atools_address_query" Android:layout_width= "mat Ch_parent "android:layout_height=" wrap_content "android:text=" number Attribution query "Android:textcolor=" @android: Color/white " Android:textsize= "20SP" Android:paddingtop= "10DP" android:paddingbottom= "10DP"/> <include layout= "@layout/line"/> <textview Android:id= "@+id/tv_atools_sms_backup" android:layout_width= "match_parent" android:layout_height= "Wrap_cont ENT "android:text=" SMS Backup "android:textcolor=" @android: Color/white "android:textsize=" 20sp "android:paddingtop=" 10DP "android:paddingbottom=" 10DP "/> <include layout=" @layout/line "/> <textview android:id=" @ +id/tv_atools_sms_restore "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Andro id:text= "SMS Restore" android:textcolor= "@android: Color/white" android:textsize= "20sp" android:paddingtop= "10DP" and roid:paddingbottom= "10DP"/> <include layout= "@layout/line"/></linearlayout>
5. Perfect Activity Class
The main function in this class is to locate the control on the page and set the control's State event to complete the response to the business in the corresponding event.
The specific implementation code is as follows:
Package Cn.lyz.mobilesafe.activity;import Java.util.list;import Android.app.activity;import Android.app.progressdialog;import Android.content.contentvalues;import Android.content.intent;import Android.net.uri;import Android.os.bundle;import Android.os.looper;import Android.os.systemclock;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.textview;import Android.widget.toast;import Cn.lyz.mobilesafe.r;import Cn.lyz.mobilesafe.domain.smsinfo;import Cn.lyz.mobilesafe.engine.smsinfoservice;import cn.lyz.mobilesafe.service.backupsmsservice;/** * Backup and restore of SMS * @author Liuyazhuang * */public class Atoolsactivity extends Activity implements Onclicklistener{private TextView Tv_atools_sms_ Backup;private TextView tv_atools_sms_restore;private progressdialog mpd;private smsinfoservice smsInfoService;@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.atools); tv_atOols_sms_backup = (TextView) Findviewbyid (r.id.tv_atools_sms_backup); Tv_atools_sms_backup.setonclicklistener (this ); Tv_atools_sms_restore = (TextView) Findviewbyid (r.id.tv_atools_sms_restore); tv_atools_sms_ Restore.setonclicklistener (this), Smsinfoservice = new Smsinfoservice (this);} public void OnClick (View v) {//TODO auto-generated method Stubint id = V.getid (), Intent Intent = Null;switch (ID) {Case R . id.tv_atools_sms_backup:intent = new Intent (This,backupsmsservice.class); StartService (intent); Break;case r.id.tv_ Atools_sms_restore:restoresms ();d efault:break;}} /** * Restore SMS Operation */private void Restoresms () {//1 Delete all SMS//2 insert the data inside the XML into the SMS database//2.1 first parse the XML file//2.2 Insert Data MPD = new Progres Sdialog (this); Mpd.settitle ("Deleting the original text message"); Mpd.setprogressstyle (progressdialog.style_horizontal); Mpd.show (); new Thread () {public void run () {try {uri uri = uri.parse ("content://sms"); Getcontentresolver (). Delete (Uri, NULL, NULL); Mpd.settitle ("Restoring SMS"); list<smsinfo> Smsinfos = Smsinfoservice.getsmsinfosfromxml (); Mpd.setmax (Smsinfos.size ()); for (Smsinfo Smsinfo:smsinfos) {contentvalues values = new Contentvalues (); Values.put (" Address ", smsinfo.getaddress ()); Values.put (" Date ", Smsinfo.getdate ()); Values.put (" Type ", Smsinfo.gettype ()); Values.put ("Body", smsinfo.getbody ()); Getcontentresolver (). Insert (URI, values); Systemclock.sleep (+); Mpd.incrementprogressby (1);//each progress bar scale value plus 1}mpd.dismiss (); Looper.prepare (); Toast.maketext (Getapplicationcontext (), "SMS Restore Succeeded", 1). Show (); Looper.loop ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); Mpd.dismiss (); Looper.prepare (); Toast.maketext (Getapplicationcontext (), "SMS Restore Failed", 1). Show (); Looper.loop ();}};}. Start ();}}
6. Add Permissions
Don't forget to register the appropriate permissions to the Androidmanifest.xml file
Specific as follows:
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android: Name= "Android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name= "android.permission.READ_ SMS "/><uses-permission android:name=" Android.permission.WRITE_SMS "/>
Third, the Operation effect
Run interface
SMS Backup Complete
Notification display
Start restoring SMS
Restoring SMS
SMS Restore Successful
Four, warm tips
In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android--Backup and restore of SMS