0

我正在开发一个备份 android 文本消息的应用程序,我能够将文本消息保存在 xml 文件中,现在我想将此文件消息导入回 android。我不知道该怎么做,任何帮助将不胜感激

4

1 回答 1

0
  • To read and parse xml file:
XmlPullParserFactory pullParserFactory;
      try {
          pullParserFactory = XmlPullParserFactory.newInstance();
          XmlPullParser parser = pullParserFactory.newPullParser();
              InputStream in_s = getApplicationContext().getAssets().open("temp.xml");
              parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
              parser.setInput(in_s, null);
              parseXML(parser);
      } catch (XmlPullParserException e) {
          e.printStackTrace();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
ArrayList<SMSMessage> smsMessages = null;
int eventType = parser.getEventType(); SMSMessage smsMessage = null;

while (eventType != XmlPullParser.END_DOCUMENT){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    smsMessages = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name == "message"){
                        smsMessage = new SMSMessage();
                    } else if (smsMessage != null){
                        if (name == "address"){
                            smsMessage.address = parser.nextText();
                        } else if (name == "body"){
                            smsMessage.body = parser.nextText();
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("message") && smsMessage != null){
                        smsMessages.add(smsMessage);
                    }
            }
            eventType = parser.next();
        }
}
  • To write messages to phone memory:

Activity:

for(SMSMessage aMessage : smsMessages){
  ContentValues my_values = new ContentValues();
  my_values.put("address", aMessage.address);
  my_values.put("body", aMessage.body);
  getContentResolver().insert(Uri.parse("content://sms/inbox"), my_values);
}

Manifest:

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

Something like that. Sources: this & that

P.S. Haven't compiled myself, mistakes are, obviously, present + SMSMessage class should be implemented, since you haven't told us what this datastructure should contain (how you structure your xml file with all the messages)

于 2013-06-27T20:29:15.513 回答