Code Analysis of Android Short Message Backup and Data Insertion

  • 2021-12-11 08:44:23
  • OfStack

Realize backing up SMS to xml file and inserting 1 piece of data like SMS

1. SMS will be backed up to xml file

Define 1 button in the layout file, and define the click event as copyClick

MainActivity. java:


package com.lgqrlchinese.heima76android_copysms;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.Toast;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
  // Dynamic access to permissions 
  static final String[] PERMISSION = new String[]{
      Manifest.permission.READ_SMS,
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Dynamic access to permissions 
    MyPermission();
  }

  // Click the button to query the contents of the SMS database, and then back up 
  public void copyClick(View view) {

    try {
      // Get xml Serialized instance 
      XmlSerializer serializer = Xml.newSerializer();
      // Setting serialization parameters 
      File file = new File(Environment.getExternalStorageDirectory().getPath(), "smsBackUp.xml");
      FileOutputStream fos = new FileOutputStream(file);
      serializer.setOutput(fos, "utf-8");
      // Start writing xml The beginning of a document 
      serializer.startDocument("utf-8", true);
      // Start writing the root node 
      serializer.startTag(null, "smss");

      // The content of the SMS database is also exposed by the content provider, so we only need to operate the database through the content parser 
      Uri uri = Uri.parse("content://sms/");
      Cursor cursor = getContentResolver().query(uri, new String[]{"address", "date", "body"}, null, null, null);
      while (cursor.moveToNext()) {
        String address = cursor.getString(0);
        String date = cursor.getString(1);
        String body = cursor.getString(2);

        // Write sms Node 
        serializer.startTag(null, "sms");

        // Write address Node 
        serializer.startTag(null, "address");
        serializer.text(address);
        serializer.endTag(null, "address");

        // Write body Node 
        serializer.startTag(null, "body");
        serializer.text(body);
        serializer.endTag(null, "body");

        // Write date Node 
        serializer.startTag(null, "date");
        serializer.text(date);
        serializer.endTag(null, "date");

        serializer.endTag(null, "sms");

      }

      serializer.endTag(null, "smss");
      serializer.endDocument();


    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.out.println(" Anomaly 1");
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println(" Anomaly 2");
    }


  }

  // Dynamic access to permissions 
  public void MyPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
      //Android 6.0 Apply for authority 
      ActivityCompat.requestPermissions(this, PERMISSION, 1);
    } else {
      Toast.makeText(this, " Success ", Toast.LENGTH_SHORT).show();
    }
  }

}

Of course, permission is necessary

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

This backs up the xml file in the root directory of the SD card

In the real machine 6.0 test, I encountered the crash of storage address, and debugged it for a long time. Print addredss first, no problem; There is no problem in storing dead data. Finally, it is found that there is an address for null in the output printing room. I checked my mobile phone because there was a draft text message, and I thought of two solutions that I could think of:

1. Delete or send drafts from your phone

2. Judge in code


if (address != null) {

          serializer.startTag(null, "address");
          serializer.text(address);
          serializer.endTag(null, "address");
        } else {
          serializer.text(" This is a draft ");
        }

2. Insert data into the database of short messages (no external application modification is allowed after 5.0, and reading is allowed directly without making too many records)


import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
  // Dynamic access to permissions 
  static final String[] PERMISSION = new String[]{
      Manifest.permission.READ_SMS,
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MyPermission();
  }

  // Click the button to insert data in the SMS database 
  public void insertClick(View view) {
    Uri uri = Uri.parse("ocntent://sms");
    ContentValues values = new ContentValues();
    values.put("address", "17865318803");
    values.put("body", " I am your shadow ");
    values.put("date", System.currentTimeMillis());
    getContentResolver().insert(uri, values);
  }

  // Dynamic access to permissions 
  public void MyPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
      //Android 6.0 Apply for authority 
      ActivityCompat.requestPermissions(this, PERMISSION, 1);
    } else {
      Toast.makeText(this, " Success ", Toast.LENGTH_SHORT).show();
    }
  }
}

Related articles: