短信备份:
- 代码实现过程
- 提供内容解析者把短信数据取出来
Uri uri = Uri.parse("content://sms/"); Cursor cursor = getContentResolver().query(uri, new String[]{"address", "body", "date"}, null, null, null); Log.e(TAG, "backup: " + (cursor == null));
-
- 使用xml序列化把数据保存到xml文件中
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Button backup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); backup = findViewById(R.id.backup); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, 1); } else { } backup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backup(); } }); } private void backup() { try { XmlSerializer xmlSerializer = Xml.newSerializer(); File file = new File(getFilesDir().getAbsolutePath(), "smsbackup.xml"); Log.e(TAG, "backup: " + getFilesDir().getAbsolutePath()); FileOutputStream fos = new FileOutputStream(file); xmlSerializer.setOutput(fos, "utf-8"); xmlSerializer.startDocument("utf-8", true); xmlSerializer.startTag(null, "smss"); Uri uri = Uri.parse("content://sms/"); Cursor cursor = getContentResolver().query(uri, new String[]{"address", "body", "date"}, null, null, null); Log.e(TAG, "backup: " + (cursor == null)); while (cursor.moveToNext()) { xmlSerializer.startTag(null, "sms"); xmlSerializer.startTag(null, "address"); Log.e(TAG, "backup: " + cursor.getString(0)); if (cursor.getString(0) == null || cursor.getString(0).equals("") || cursor.getString(0).equals(null)) { xmlSerializer.text(""); } else { xmlSerializer.text(cursor.getString(0)); } xmlSerializer.endTag(null, "address"); xmlSerializer.startTag(null, "body"); Log.e(TAG, "backup: " + cursor.getString(1)); if (cursor.getString(1) == null || cursor.getString(1).equals("") || cursor.getString(1).equals(null)) { xmlSerializer.text(""); } else { xmlSerializer.text(cursor.getString(1)); } xmlSerializer.endTag(null, "body"); xmlSerializer.startTag(null, "date"); Log.e(TAG, "backup: " + cursor.getString(2)); if (cursor.getString(2) == null || cursor.getString(2).equals("") || cursor.getString(2).equals(null)) { xmlSerializer.text(""); } else { xmlSerializer.text(cursor.getString(2)); } xmlSerializer.endTag(null, "date"); xmlSerializer.endTag(null, "sms"); Log.e(TAG, "backup: 2222"); } Log.e(TAG, "backup: 3333"); xmlSerializer.endTag(null, "smss"); xmlSerializer.endDocument(); Toast.makeText(this, "备份成功", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e(TAG, "backup: " + e.getLocalizedMessage().toString()); Toast.makeText(this, "备份失败", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }}