我正在尝试在android中使用ical4j解析谷歌日历ical(.ics)文件。但从输入流构建日历需要40多秒。
calendar = builder.build(fis);
ical文件的大小只有150KB。此外,当我使用相同的代码并在PC上运行时,日历的构建将在不到一秒钟的时间内完成。我还注意到LogCat中有大量的垃圾收集。有人能帮我吗?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView = (TextView)findViewById(R.id.Hello_World);
new Download().execute();
}
final class Download extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute(){
TextView.setText("Downloading");
}
@Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = openFileOutput(fileName, MainActivity.MODE_PRIVATE);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
return null;
}
@Override
protected void onPostExecute(Void Result) {
TextView.setText("Saved...Loading Data");
new Loadicaldata().execute();
}
}
final class Loadicaldata extends AsyncTask<Void, Void, Void> {
String Summary = null;
@Override
protected Void doInBackground(Void... arg0) {
FileInputStream fis = null;
try {
fis = openFileInput(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = null;
try {
calendar = builder.build(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b.append(calendar.getProperty("X-WR-CALNAME").getValue());
ComponentList events = calendar.getComponents(Component.VEVENT);
VEvent Event = (VEvent) events.get(0);
Summary = Event.getDescription().getValue();
/*
for (Object event : calendar.getComponents(Component.VEVENT)) {
if (((VEvent) event).getSummary() != null) {
b.append("nn");
b.append(((VEvent) event).getSummary().getValue());
b.append(": ");
b.append(((VEvent) event).getStartDate().getDate());
}
}
*/
return null;
}
@Override
protected void onPostExecute(Void Result) {
TextView.setText(Summary);
}
}
LogCat:http://dl.dropbox.com/u/35866688/LogCat.txt
此外,我可以安全地排除IO错误的可能性,因为Calendar.load方法也需要那么长的时间。
如果有人感兴趣,这就是ical文件。https://www.google.com/calendar/ical/m0es4hhj4g9d69ibak88tvoup0%40group.calendar.google.com/public/basic.ics
一种可能性是,您正在doInBackground
方法中读取未缓冲的输入流。如果CalendarBuilder.build(...)
方法一次读取一个字节,这将生成大量的系统调用,并显著降低速度。
第二种可能性是问题是由垃圾收集引起的。对此你无能为力,但增加堆大小可能会有帮助。(GC开销过大的一个原因是运行的堆接近满。如果GC无法在每个GC周期中回收大量内存,则GC的效率会严重下降…)