短信备份的原理——使用内容提供者

    public class MainActivity extends Activity {

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

    public void backup(View view){
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://sms");
        Cursor cursor = resolver.query(uri, null, null, null, null);



        try {
            XmlSerializer serializer = Xml.newSerializer();
            File file = new File(Environment.getExternalStorageDirectory(),"back.xml");
            OutputStream os = new FileOutputStream(file);

            serializer.setOutput(os, "UTF-8");
            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "smss");
            while(cursor.moveToNext()){
                serializer.startTag(null, "sms");
                    serializer.startTag(null, "address");
                    String address = cursor.getString(cursor.getColumnIndex("address"));
                    serializer.text(address);
                    serializer.endTag(null, "address");

                    serializer.startTag(null, "body");
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    serializer.text(body);
                    serializer.endTag(null, "body");

                    serializer.startTag(null, "date");
                    long date = cursor.getLong(cursor.getColumnIndex("date"));
                    String dateString = new Date(date).toString();
                    serializer.text(dateString);
                    serializer.endTag(null, "date");

                serializer.endTag(null, "sms");
            }

            serializer.endTag(null, "smss");
            serializer.endDocument();
            os.close();
            Toast.makeText(this, "备份成功",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(安卓开发之旅)