我有一个显示4个内容丰富的片段的活动,所有片段都在屏幕上显示,因此开始活动总是很慢,因为每个片段需要先在各自的AsyncTasks中获取数据显示。
目前,我正在OnCreate()中为IdleActivity加载所有片段,但是这是一个很棒的事情,所需的对象被GC用于腾出空间,显然不是正确/最好的方法。
片段始终相同,并且硬编码到活动的布局xml中
我已经考虑过实现一个'队列'来逐个加载片段,希望加载它的数据,显示它然后才开始加载下一个片段。或者,我可以为每个片段创建一个单独的线程,负责仅启动其片段,然后与它们一起进行整个synchronized, notify, wait
游戏,但这似乎很浪费。这样做的最佳方式是什么?
我不确定在活动将其视图显示在屏幕上之后,如何在之后调用片段,因为否则应用程序似乎挂在活动之间。在加载和显示活动时如何调用方法?
onCreate Code,如果有任何用处:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_idle);
showProgressDialog();
notifFrag = (notifFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_notif);
forecastFrag = new forecastFragment();
currentInfoFrag = new currentInfoFragment();
calendarFrag = new calendarFragment();
notifDisplayHandler = new Handler();
weatherUpdateHandler = new Handler();
calendarUpdateHandler = new Handler();
hideProgressDialog();
}
处理内容的主题:
private final Runnable notifUpdateThread = new Runnable() {
@Override
public void run() {
//Display the notifications
//Index is handled internally by the fragment
notifFrag.displayNotifsView();
Log.i(TAG, "Notification Thread runs update");
//Display each notif for 10 seconds
notifDisplayHandler.postDelayed(notifUpdateThread, 10000);
}
};
private currentInfoFragment currentInfoFrag;
private forecastFragment forecastFrag;
private final Runnable weatherUpdateThread = new Runnable() {
@Override
public void run() {
//The callbacks for these are implemented in the respective fragments
// so calling this updates the fragments as well
currentInfoFrag.updateWeather(IdleActivity.this);
forecastFrag.updateWeather(IdleActivity.this);
Log.i(TAG, "Weather Thread runs updates");
//Refreshes weather data every 20 minutes
weatherUpdateHandler.postDelayed(weatherUpdateThread, 1200000);
}
};
private calendarFragment calendarFrag;
private final Runnable calendarUpdateThread = new Runnable() {
@Override
public void run() {
calendarFrag.populateCalendar(IdleActivity.this);
Log.i(TAG, "Calendar Thread runs update");
//Run next update in 4 Hours
calendarUpdateHandler.postDelayed(calendarUpdateThread, 14400000);
}
};
当活动附加到窗口时启动线程:
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
//Handle loading of content
notifDisplayHandler.postDelayed(notifUpdateThread, 10000);
weatherUpdateHandler.post(weatherUpdateThread);
calendarUpdateHandler.post(calendarUpdateThread);
}
结构:
IdleActivity
-CalendarFragment
-CurrentWeatherFragment
-ForecastFragment
-NotificationsFragment
提前致谢!