【发布时间】:2015-08-17 13:17:59
【问题描述】:
在我的 android 应用程序项目中启动 Activity 时遇到延迟。
每当单击菜单项或可单击视图时,onClickListener 只会创建一个新 Intent 并启动指定的活动。到目前为止没关系。但是,在用户看到新活动之前,视图会被冻结一段明显的时间(大约 1 秒)。
那个时间可能是onCreate里面的进度造成的,但是我用System.currentTimeMillis()测量了时间,最后在logcat中打印出来了。因此,它似乎只需要 20-30 毫秒,并且在用户看到活动之前很久就打印了日志。
这是我的代码:
public class ExampleActivity extends MyActivity {
MyModel myModel;
long startTime;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startTime = System.currentTimeMillis();
setContentView(R.layout.activity_ders_programi);
setToolbar();
myModel = Controller.getMyModel();
if(myModel == null) { //If we don't have the object previously
//this fills the object, takes some time
myModel = new MyModel(this);
//myModel is observable and this activity is observer.
//Whenever it's done, it notifies this activity
}
else //If we got the object previously
createCardViews();
Controller.setMyModel(myModel);
setParentActivity();
}
//If Observable object notifies this activity, update() is called.
@Override
public void update(Observable observable, Object o) {
createCardViews();
}
//Creating a list of cardViews, this also takes some time
private void createCardViews() {
ArrayList<Card> cards = new ArrayList<Card>();
for(int i = 0; i < 5; i++) {
MyModelCardModel card = new MyModelCardModel(this, i);
card.init();
cards.add(card);
}
CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(this,cards);
CardListView listView = (CardListView) findViewById(R.id.my_card_list_view);
if (listView!=null)
listView.setAdapter(mCardArrayAdapter);
//I think here is the last point.
//After this point there will be no significant process.
long stopTime = System.currentTimeMillis();
Log.d("modelflow", "card create takes: " + (stopTime - startTime) + "ms");
}
那我做错了什么?如果延迟是因为进度很重,那么为什么测量的时间似乎很少。假设进度导致延迟,为什么应用程序在显示活动后不等待?以及如何避免这种情况?
【问题讨论】:
-
你如何衡量这个时间?它是调试版本吗?你在调试模式下测量你的时间吗?什么是操作系统版本和设备型号?
-
@ViktorYakunin 正如您在上面的代码中看到的,我使用了两个变量,分别名为 startTime 和 stopTime。最后,我将它们之间的差异打印到 logcat。我没有使用调试模式。 Applicaiton 在我自己的手机三星 Galaxy S4 上运行,操作系统是 Android 4.4.2。但在模拟器中同样的问题,Nexus S with Android 5.0
-
尝试将密集处理代码移动到另一个生命周期方法中 - 可能是
onResume(),然后查看延迟是否消失。 -
@Safa Kadir 您的问题并不明显,以防万一,与发布版本相比,调试版本未优化并且性能不佳。
-
@nightfixed 记得我试过了,但延迟并没有消失。但那是在一些变化之前。我会再试一次。
标签: android android-activity delay