Android LoaderManager AsyncTaskLoader,Kotlin(4)- 

时间:2024-10-30 10:28:18

 

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(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()
        //触发 loadInBackground()
        manager?.getLoader<MyData>(loaderId)?.onContentChanged()
    }

    class MyLoader(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 {
            var d = MyData("${System.currentTimeMillis()}")
            Log.d(TAG, "loadInBackground @ ${d.value}")
            return d
        }

        //工作在主线程。data是loadInBackground()返回的值。
        override fun deliverResult(data: MyData?) {
            super.deliverResult(data)
            Log.d(TAG, "deliverResult ${data?.value}")
        }
    }

    data class MyData(val value: String)
}

 

 

启动后:

D  onCreateLoader 0

D  onStartLoading

 

按home键,把应用切入后台不可见:

D  forceLoad

D onContentChanged

D loadInBackground @ 1729932886262

D  onLoadFinished 2024 MyData(value=1729932886262)

D  deliverResult 1729932886262

 

 

 

 

Android LoaderManager AsyncTaskLoader Kotlin(3)-****博客文章浏览阅读774次,点赞5次,收藏24次。android LoaderManager与AsyncTaskLoader,java(1)_zhangphil的博客-****博客。android LoaderManager与AsyncTaskLoader,java(1)_android loadermanager 和 asynctaskloader。android LoaderManager与AsyncTaskLoader,java(1)_android loadermanager 和 asynctaskloader-****博客。https://zhangphil.blog.****.net/article/details/143291905