Backup and reply to Android SMS

Source: Internet
Author: User

In Android Backup SMS and restore SMS is very important to save information to avoid deletion of important information can not be saved, here is the operation of the SMS database, note: In Android for other applications in the database operation can not be in the form of database objects must be escaped with a URI Uri uri = Uri.parser ("content://sms/");

Need to add permissions to the SMS database operation

<uses-permission android:name= "Android.permission.READ_SMS"/>
<uses-permission android:name= "Android.permission.WRITE_SMS"/>

First, let's look at the structure of the SMS database pull out the SMS database in Eclipse in File Explorer data/

Open with SQLite expert,, the main use of the table is the SMS its structure such as

Describe the meaning of each column: ID not much is the corresponding ID number in this table thread_id is used to identify is not the same number to send or receive information on the identity address to send the object's mobile phone number SMS source phone number, read 1 represents has read 0 representative did not read, Type is used to determine whether to send or receive a 1 representative to send 2 to receive, body is the text message content entity,

We need to create a new information entity in the program:

Package com.example.mobilesafe.domain;
public class Smsinfo {
String _id;
int type;//determine whether to send or receive
String address;//send or receive number
String body;//SMS Content
String date;//time to send or receive text messages

@Override
Public String toString () {
Return "Smsinfo [_id=" + _id + ", type=" + Type + ", address="
+ Address + ", body=" + Body + ", date=" + Date + "]";
}
Construction method
Public Smsinfo (string _id, int type, string address, string body, string date) {
Super ();
this._id = _id;
This.type = type;
this.address = address;
This.body = body;
This.date = date;
}

Public String get_id () {
return _id;
}
public void set_id (String _id) {
this._id = _id;
}
public int GetType () {
return type;
}
public void SetType (int type) {
This.type = type;
}
Public String getaddress () {
return address;
}
public void setaddress (String address) {
this.address = address;
}
Public String GetBody () {
return body;
}
public void Setbody (String body) {
This.body = body;
}
Public String getDate () {
return date;
}
public void SetDate (String date) {
This.date = date;
}

}

Then write a function to read the text and reply to the message

Package com.example.mobilesafe.engine;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import java.util.ArrayList;
Import java.util.List;
Import Org.xmlpull.v1.XmlPullParser;
Import org.xmlpull.v1.XmlPullParserException;
Import Android.app.Dialog;
Import Android.app.ProgressDialog;
Import Android.content.ContentResolver;
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.os.Looper;
Import android.provider.ContactsContract.CommonDataKinds.Event;
Import Android.util.Log;
Import android.util.Xml;
Import Android.widget.Toast;
Import Com.example.mobilesafe.domain.SMSInfo;

In this class to achieve the reading and recovery of SMS
public class Smsinfoservice {
private static final String TAG = "Smsinfoservice";
Private context context;

Public Smsinfoservice (Context context) {
This.context = context;//passing the context in
}
/**
* Backup Information
* @return
*/
Public list<smsinfo> Getsmsinfos () {
list<smsinfo> Smsinfos = new arraylist<smsinfo> ();
Contentresolver contentresolver = Context.getcontentresolver ();//This contentresolver is used for database operations on other applications.
Unable to transfer the database direct operation to the SMS
Uri uri = uri.parse ("content://sms/");
/**
* Describes the parameters of the following function the first is the URI of the database The second is the column that is returned the third is the row that is returned fourth do not know what the fifth is set to sort by
*/
cursor cursor = contentresolver.query (URI, NULL, NULL, NULL, NULL);
LOG.I (TAG, "SHIFOUJINRU cursor");
if (null! = cursor) {
LOG.I (TAG, "Querying the data entry in the SMS Database" +cursor.getcount ());
while (Cursor.movetonext ()) {
String _id = cursor.getstring (Cursor.getcolumnindex ("_id"));
int type = Cursor.getint (Cursor.getcolumnindex ("type"));
String date = cursor.getstring (Cursor.getcolumnindex ("date"));
String address = cursor.getstring (Cursor.getcolumnindex ("Address"));
String BODY = cursor.getstring (Cursor.getcolumnindex ("body"));
Smsinfo smsinfo = new Smsinfo (_id, type, address, body, date);

System.out.println (Smsinfo);
Smsinfos.add (Smsinfo);
}
Cursor.close ();
}
return Smsinfos;

}
/**
*
* Enter the path of the saved SMS @param path
* @param PD incoming formal parameter Diaolog
* @throws Exception
* @throws Exception
*/
public void Restoresms (String path,progressdialog PD) throws Exception {//database operation on SMS cannot directly use the database operation must be escaped

File File = new file (path);//need to parse the XML file for this file
Xmlpullparser parser = Xml.newpullparser ();//parse Xml file using Pullparser
FileInputStream fis = new FileInputStream (file);
Parser.setinput (FIS, "utf-8");
Contentvalues values = null;
int type = Parser.geteventtype ();
int currentcount=0;
while (type! = xmlpullparser.end_document) {//if not to the end of the file is always executed
Switch (type) {
Case xmlpullparser.start_tag://Start node
if ("Count". Equals (Parser.getname ())) {
Pd.setmax (Integer.parseint (Parser.nexttext ()));//Set the maximum value for the dialog box
}else if ("SMS". Equals (Parser.getname ())) {///But the information node creates a new contentvalues
values = new Contentvalues ();
}else if ("_id". Equals (Parser.getname ())) {//Gets the name of the node if it is an ID
Values.put ("_id", Parser.nexttext ());
}else if ("Address". Equals (Parser.getname ())) {
Values.put ("Address", Parser.nexttext ());
}else if ("Date". Equals (Parser.getname ())) {
Values.put ("Date", Parser.nexttext ());
}else if ("type". Equals (Parser.getname ())) {
Values.put ("type", Parser.nexttext ());
}else if ("Body". Equals (Parser.getname ())) {
Values.put ("Body", Parser.nexttext ());
}
Break
Case xmlpullparser.end_tag:{
if ("SMS". Equals (Parser.getname ())) {//If the node is SMS
Uri uri = uri.parse ("content://sms/");
Contentresolver resolver = Context.getcontentresolver ();
Resolver.insert (URI, values);//Insert data into the database first
Values =null;//

currentcount++;
Pd.setprogress (Currentcount);//Set Progress
}
}
Default
Break
}
Type = Parser.next ();//Do not forget to re-assign a value to type
}



}
}

Here we save the text message in XML form, which will use the Xmlpuuparser and XmlSerializer two objects.

Read the backup function as follows

Package com.example.mobilesafe.service;


Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.util.ArrayList;


Import Org.xmlpull.v1.XmlPullParser;
Import Org.xmlpull.v1.XmlSerializer;


Import Com.example.mobilesafe.domain.SMSInfo;
Import Com.example.mobilesafe.engine.SmsInfoService;


Import Android. R.xml;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import Android.os.Looper;
Import android.util.Xml;
Import Android.widget.Toast;
/**
* Back up SMS in this service
* @author Administrator
*
*/
public class Backupsmsservice extends Service {
This service will involve reading the SMS database and saving the read data to an XML file

Private Smsinfoservice Smsinfoservice;
@Override
Public IBinder Onbind (Intent Intent) {
TODO auto-generated Method Stub
return null;
}


@Override
public void OnCreate () {
Super.oncreate ();
Smsinfoservice = new Smsinfoservice (this);
Use a thread in this service to read the database and write it to an XML file.
New Thread () {


@Override
public void Run () {
TODO auto-generated Method Stub
Super.run ();

try {
arraylist<smsinfo> list = (arraylist<smsinfo>) Smsinfoservice.getsmsinfos ();//Get the return value of the SMS
XmlSerializer XmlSerializer = Xml.newserializer ();//Create a new class that can store Xml ' to file
File File = new file ("/sdcard/backupsms.xml");
FileOutputStream fos = new FileOutputStream (file);
Xmlserializer.setoutput (FOS, "utf-8");
Xmlserializer.startdocument ("Utf-8", true);
Xmlserializer.starttag (NULL, "SMSS");
Add a node to calculate the percentage of dialog

Xmlserializer.starttag (NULL, "count");
Xmlserializer.text (list.size () + "");
Xmlserializer.endtag (NULL, "count");
for (Smsinfo smsinfo:list) {
Xmlserializer.starttag (NULL, "SMS");

Xmlserializer.starttag (NULL, "id");
Xmlserializer.text (smsinfo.get_id ());
System.out.println (smsinfo.get_id ());
Xmlserializer.endtag (NULL, "id");

Xmlserializer.starttag (NULL, "address");
Xmlserializer.text (Smsinfo.getaddress ());
System.out.println (Smsinfo.getaddress ());
Xmlserializer.endtag (NULL, "address");

Xmlserializer.starttag (NULL, "date");
Xmlserializer.text (Smsinfo.getdate ());
Xmlserializer.endtag (NULL, "date");

Xmlserializer.starttag (NULL, "type");
Xmlserializer.text (Smsinfo.gettype () + "");
Xmlserializer.endtag (NULL, "type");

Xmlserializer.starttag (NULL, "body");
Xmlserializer.text (Smsinfo.getbody ());
System.out.println (Smsinfo.getbody ());
Xmlserializer.endtag (NULL, "body");

Xmlserializer.endtag (NULL, "SMS");
}
Xmlserializer.endtag (NULL, "SMSS");
Xmlserializer.enddocument ();//Must end
Fos.flush ();
Fos.close ();
Create a message loop to show when write is complete
Looper.prepare ();
Toast.maketext (Getapplicationcontext (), "Backup Complete", Toast.length_short). Show ();
Looper.loop ();//This statement is the execution of a message loop

} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
Create a message loop to show when write is complete
Looper.prepare ();
Toast.maketext (Getapplicationcontext (), "Backup Failed", Toast.length_short). Show ();
Looper.loop ();//This statement is the execution of a message loop
}
}


}.start ();

}

}

The reply to the SMS is simple, just call the function public void restoresms (String path,progressdialog PD) just fine.

Backup and reply to Android SMS

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.