Jetpack组件WorkManager简单demo

1.WorkManager

WorkManager,个人理解它是一个后台任务管理器,可以保证那些不一定即时完成但一定要完成的任务,WorkManager必须工作在jdk1.8以上
使用前先添加依赖:implementation "androidx.work:work-runtime-ktx:2.1.0
如果代码没错,但是就是编译不通过,可以参考GitHub上的build.gradle配置

2.继承Work类,写自己的work类:AppDatabaseWorker

AppDatabaseWorker类是在数据库被创建伊始时,往数据库内添加数据

package com.example.ngsl.room

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.example.ngsl.WORD_JSON_FILE_NAME
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import kotlinx.coroutines.coroutineScope

//新建数据库时,会执行以下任务:将json文件导入数据库
//这里我继承的是CoroutineWorker,一个协程工作者
class AppDatabaseWorker(context: Context, workerParams: WorkerParameters) :
    CoroutineWorker(context, workerParams) {
    //必须重载doWork方法
    override suspend fun doWork(): Result = coroutineScope {
    	//整个try就是你想实现的功能,最后一定也要有Result.success()语句
        try {
            applicationContext.assets.open(WORD_JSON_FILE_NAME).use { inputStream ->
                JsonReader(inputStream.reader()).use { jsonReader ->
                	//读取JSON文件
                    val wordType = object : TypeToken<List<Word>>() {}.type
                    val wordList: List<Word> = Gson().fromJson(jsonReader, wordType)
					//写入数据库
                    val wordRepository = WordRepository.getInstance(applicationContext)
                    wordRepository.insertAll(wordList)

                    Result.success()
                }
            }
        } catch (ex: Exception) {
            Log.e(TAG, "Error seeding database", ex)
            Result.failure()
        }
    }

    companion object {
    	//打印日志的标签
        private val TAG = AppDatabaseWorker::class.java.simpleName
    }
}

3.调用WorkManager

这是我的一个数据库类AppDatabase ,在被创建伊始时,往数据库内添加数据

package com.example.ngsl.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.example.ngsl.DATABASE_NAME

@Database(entities = [Word::class] , version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun wordDao(): WordDao

    companion object {
        // 保证单例模式
        @Volatile private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        // 创建数据库
        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
                .addCallback(object : RoomDatabase.Callback() {
                    override fun onCreate(db: SupportSQLiteDatabase) {
                        super.onCreate(db)
                        //调用WorkManager,OneTimeWorkRequestBuilder表示一次提交完成任务
                        val request = OneTimeWorkRequestBuilder<AppDatabaseWorker>().build()
                        WorkManager.getInstance(context).enqueue(request)
                    }
                })
                .build()
        }
    }
}

4.GitHub源码链接

整个项目有很多组件,只看你需要的部分:https://github.com/YDDUONG/NGSL-English
如果觉得有用,点个赞吧

你可能感兴趣的:(Android)