游标cursor的get不是一定要用int 都用string也是可以的
因为在数据库里面全部都是string 只不过是说自己知道什么类型,用getInt就不用自己再去转化一次
通过XmlSerializer对xml进行序列化到本地。
package com.heima.sms; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlSerializer; import com.heima.sms.entites.SmsInfo; import android.app.Activity; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Xml; import android.view.View; import android.widget.Toast; public class SMSActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); } //Button按钮 public void backupSms(View v){ //查处所有短信 Uri uri = Uri.parse("content://sms"); ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"_id","address","date","type","body"}, null, null, null); if(cursor!=null && cursor.getCount()>0){ List<SmsInfo> smsList = new ArrayList<SmsInfo>(); SmsInfo sms; while(cursor.moveToNext()){ sms = new SmsInfo(); //get不是一定要用int 都用string也是可以的 //因为在数据库里面全部都是string 只不过是说自己知道什么类型,用getInt就不用自己再去转化一次 sms.setId(cursor.getInt(0)); sms.setAddress(cursor.getString(1)); sms.setDate(cursor.getLong(2)); sms.setType(cursor.getInt(3)); //短信的类型,接收是1 发送是2 sms.setBody(cursor.getString(4)); smsList.add(sms); } cursor.close(); //序列化存在本地 writeToLocal(smsList); } } private void writeToLocal(List<SmsInfo> smsList) { // TODO Auto-generated method stub try { XmlSerializer serializer = Xml.newSerializer(); //得到序列化对象 FileOutputStream fos = new FileOutputStream(new File( Environment.getExternalStorageDirectory().getPath(), "sms.xml")); serializer.setOutput(fos, "utf-8"); serializer.startDocument("utf-8", true); serializer.startTag(null, "smss"); for(SmsInfo smsInfo : smsList){ serializer.startTag(null, "sms"); serializer.attribute(null, "id", smsInfo.getId()+""); serializer.startTag(null, "address"); serializer.text(smsInfo.getAddress()); serializer.endTag(null, "address"); serializer.startTag(null, "date"); serializer.text(String.valueOf(smsInfo.getDate())); serializer.endTag(null, "date"); serializer.startTag(null, "type"); serializer.text(String.valueOf(smsInfo.getType())); serializer.endTag(null, "type"); serializer.startTag(null, "body"); serializer.text(smsInfo.getBody()); serializer.endTag(null, "body"); serializer.endTag(null, "sms"); } serializer.endTag(null, "smss"); serializer.endDocument(); Toast.makeText(this, "备份成功", 0).show(); } catch (Exception e) { // TODO: handle exception Toast.makeText(this, "备份失败", 0).show(); } } }
读外部sd卡和sms信息的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_SMS"/>