Android LoaderManager AsyncTaskLoader Kotlin(3)
import android.content.Context
import androidx.loader.app.LoaderManager
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.loader.content.AsyncTaskLoader
import androidx.loader.content.Loader
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "fly"
}
private val loaderId = 2024
private var manager: LoaderManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val ctx = this
manager = LoaderManager.getInstance(this)
manager?.initLoader(loaderId, Bundle(), object : LoaderManager.LoaderCallbacks<MyData> {
override fun onCreateLoader(id: Int, args: Bundle?): Loader<MyData> {
val loader = MyLoader<MyData>(ctx)
Log.d(TAG, "onCreateLoader ${loader.id}")
return loader
}
override fun onLoaderReset(loader: Loader<MyData>) {
Log.d(TAG, "onLoaderReset ${loader.id}")
}
override fun onLoadFinished(loader: Loader<MyData>, data: MyData?) {
Log.d(TAG, "onLoadFinished ${loader.id} $data")
}
})
}
override fun onPause() {
super.onPause()
manager?.getLoader<MyData>(loaderId)?.onContentChanged()
}
class MyLoader<MyData>(ctx: Context) : AsyncTaskLoader<MyData>(ctx) {
override fun onContentChanged() {
super.onContentChanged()
Log.d(TAG, "onContentChanged")
}
override fun onStartLoading() {
super.onStartLoading()
Log.d(TAG, "onStartLoading")
}
override fun forceLoad() {
super.forceLoad()
Log.d(TAG, "forceLoad")
}
override fun loadInBackground(): MyData? {
Log.d(TAG, "loadInBackground")
return null
}
override fun deliverResult(data: MyData?) {
super.deliverResult(data)
Log.d(TAG, "deliverResult")
}
}
class MyData {
}
}
当启动后:
D onCreateLoader 0
D onStartLoading
过了一会,把测试程序切入后台不可见,目的是想通过onContentChanged()触发loader加载后台任务:
D onCreateLoader 0
D onStartLoading
D forceLoad
D onContentChanged
D loadInBackground
D onLoadFinished 2024 null
D deliverResult
特别注意,以上只有loadInBackground运行在后台线程,其他均运行在main thread:
29069-29265 D loadInBackground