Android-text message backup and Restoration

Source: Internet
Author: User

Android-text message backup and Restoration

 

Currently, some Android mobile phone software can back up and restore mobile phone text messages. This blog post will introduce how to back up and restore Android text messages. Well, I believe you are still interested in these practical functions. Let's go to the topic.

I. Principles

My implementation principle is very simple. There are several TextView lists on the interface, two of which are "text message backup" and "text message restoration". Click "text message backup ", read all the text message information and save the text message information in an xml file. The xml file is placed in the sdcard and used as the backup file of the text message. When you need to restore the text message, you only need to click "text message restore". At this time, the program will first Delete the existing text message on the mobile phone, and then read the text message content backed up earlier from the text message backup xml file, write it into the SMS database.

The principle is over, isn't it easy? Next, let's implement these functions together!

Ii. Practice 1. Create an SMS entity class SmsInfo

To make the program more object-oriented and more object-oriented, I encapsulated the text message information into an entity class SmsInfo.

The Code is as follows:

 

Package cn. lyz. mobilesafe. domain;/*** text message content entity class * @ author liuyazhuang **/public class SmsInfo {// phone number private String address; // 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. address = 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 SmsInfoService

This class encapsulates operations on text message data and write and parse operations on xml files. The backup text message process is to first read the text message from the text message database, and then write the text message into the xml file. The process of restoring the text message is to delete the text message from the mobile phone, parse the backup text message file, and write the parsed text message information to the text message 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 for retrieving text message content * @ author liuyazhuang **/public class SmsInfoService {private Context context; public SmsInfoService (Context context) {// TODO Auto-generated constructor stubthis. context = context;} // obtain the public List of all text messages.
 
  
GetSmsInfos () {List
  
   
SmsInfos = new ArrayList
   
    
(); Uri uri = Uri. parse (content: // sms); Cursor c = context. getContentResolver (). query (uri, new String [] {address, date, type, body}, 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 the text message data to the xml file public void createXml (List
    
     
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 ();} // obtain the public List of SMS data from the xml file
     
      
GetSmsInfosFromXml () throws Exception {List
      
        SmsInfos = null; SmsInfo smsInfo = null; XmlPullParser parser = Xml. newPullParser (); File file = new File (Environment. getExternalStorageDirectory (), smsbackup. xml); InputStream inputStream = new FileInputStream (file); parser. 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
       
         ();} 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 = null;} break; default: break;} eventType = parser. next () ;}return smsInfos ;}}
       
      
     
    
   
  
 

 

3. Create BackupSmsService

This class is mainly used to back up text messages, and put the backup text message operation in a service class for execution, because the operation to read the database is a time-consuming operation, therefore, I have enabled a thread in this class to back up text messages. If the Backup Message fails, the user is prompted to fail to back up the text message. If the Backup Message is successful, an external notification is sent, the system prompts that the text message is successfully backed up. Stop the service after the operation is completed.

The specific implementation code is as follows:

 

Package cn. lyz. mobilesafe. service; import java. util. list; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingIntent; import android. app. service; import android. content. context; import android. content. intent; import android. OS. IBinder; import android. OS. logoff; 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;/*** backup SMS Service class * @ author liuyazhuang **/public class BackupSmsService extends Service {private SmsInfoService smsInfoService; private icationicationmanager nm; @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); smsInfoService = new SmsInfoService (this); nm = (icationicationmanager) getSystemService (Context. NOTIFICATION_SERVICE); new Thread () {public void run () {// 1 get all text messages // 2 generate an xml file List
 
  
SmsInfos = smsInfoService. getSmsInfos (); try {smsInfoService. createXml (smsInfos); // sends a Notification to notify the user of the backup completion notification = new Notification (R. drawable. notification, SMS backup is complete, System. currentTimeMillis (); Intent intent = new Intent (getApplicationContext (), MainActivity. class); PendingIntent contentIntent = PendingIntent. getActivity (getApplicationContext (), 100, intent, 0); notification. setLatestEventInfo (getApplicationContext (), prompting message, contentIntent after text message backup is complete); // click notification to automatically disappear notification. flags = Notification. FLAG_AUTO_CANCEL; nm. Y (100, notification);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); // logoff is a message pump. It extracts messages from MessageQueue and delivers the messages to Handler to process logoff. prepare (); Toast. makeText (getApplicationContext (), SMS backup failed, 0 ). show (); logoff. loop () ;}stopself (); // stop the service };}. start () ;}@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null ;}}
 

 

4. layout implementation

The specific implementation code is as follows:

 

 
     
          
           
            
             
       
        
         
          
           
           
          
         
        
       
      
     
    
   
  
 

 

5. Improve the Activity class

The main function of this class is to find the control on the page, set the control status event, and 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. logoff; 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;/*** text message backup and restoration * @ author liuyazhuang **/public class AtoolsActivity extends Activity implements OnClickListener {private TextView listener; 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); publish (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 (); default: break;}/*** restore SMS operation */private void restoreSms () {// 1 Delete all text messages // 2 insert data in xml into the text message database // 2.1 parse the xml file first // 2.2 Insert data mPd = new ProgressDialog (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
 
  
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 (2000); mPd. incrementProgressBy (1); // Add 1} mPd to the scale value of each progress bar. dismiss (); logoff. prepare (); Toast. makeText (getApplicationContext (), SMS restored successfully, 1 ). show (); logoff. loop ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); mPd. dismiss (); logoff. prepare (); Toast. makeText (getApplicationContext (), SMS restoration failed, 1 ). show (); logoff. loop ();}};}. start ();}}
 

 

6. Add Permissions

Do not forget to register the corresponding permissions with the AndroidManifest. xml file.

The details are as follows:

 

 
  
   
    
   
  
 

 

Iii. Running Effect

Run Interface

SMS backup complete

Notification display

Start to restore SMS

Restoring SMS

SMS restored successfully

4. Tips

In this example, for the purpose of writing some text directly in the layout file and related classes, you need to write these words in the real project. in xml files, reference these resources externally. Remember, this is the most basic development knowledge and specification for an Android programmer. I am writing these resources in the class and layout files for convenience.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.