简体   繁体   English

如何在Activity中实例化对象并等待其完成加载

[英]How to instantiate an object in an Activity and wait for it to finish loading

I have an activity DisplayResults that gets started from my MainActivity . 我有一个从MainActivity开始的活动DisplayResults。 In the DisplayResultsActivity , it creates an object of a custom class ProductFinder in its onCreate() function. DisplayResultsActivity ,它在其onCreate()函数中创建自定义类ProductFinder的对象。 In ProductFinder's constructor, there is a while loop that takes about 10 seconds to execute. 在ProductFinder的构造函数中,有一个while循环需要大约10秒才能执行。

My problem is that when I start DisplayResult from MainActivity , the whole screen goes black for the duration of the while loop, then finally the DisplayResults activity shows on the screen with everything. 我的问题是,当我从MainActivity启动DisplayResult时,在while循环期间,整个屏幕变黑,然后最终DisplayResults活动与所有内容一起显示在屏幕上。

What I would like is to draw the DisplayResults activity normally, then wait for the loop in the ProductFinder class to finish what it's doing without having the entire UI freeze. 我想要的是正常绘制DisplayResults活动,然后等待ProductFinder类中的循环完成其工作,而不会冻结整个UI。 Having a loading circle in the middle of DisplayResults while the loop is running would be nice. 在循环运行时,在DisplayResults的中间放置一个加载圈会很好。

What is the proper method of doing this? 这样做的正确方法是什么? I know that something needs to go in a thread, but I'm not sure which class to put the loading circle in and which code to put inside the thread. 我知道线程中需要包含某些内容,但是我不确定将加载循环放入哪个类以及将哪些代码放入线程中。

It is all depends on the requirements 一切取决于要求

As stated, you can use AsyncTask to do the job but you might get issues such as memory leaks and handling configuration changes(eg device rotation). 如前所述,您可以使用AsyncTask来完成这项工作,但是您可能会遇到诸如内存泄漏和处理配置更改(例如设备旋转)之类的问题。

Second option would be to use AsyncTaskLoader which will let you handle configuration changes ( Difference between AsyncTask to AsyncTaskLoader by Google ). 第二种选择是使用AsyncTaskLoader ,它可以让您处理配置更改( Google将AsyncTask与AsyncTaskLoader之间的区别 )。

Third option, and newer approach, would be to subscribe to ViewModel with MutableLiveData attached to the activity with a background thread to pass the states values (you can also use AsyncTask to manage the states) 第三种选择和更新的方法是,使用带有后台线程的MutableLiveData订阅ViewModel并通过后台线程传递状态值(您也可以使用AsyncTask来管理状态)

Last option (maybe the first) would be to use RxAndroid 最后一个选项(也许第一个)是使用RxAndroid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM