Android中WorkManager的简单使用
Android中WorkManager的简单使用
1.简介:
WorkManager:
WorkManager是Google推出的一个新组件,用于替代传统的Service进行后台任务处理。它的主要特点包括:
- 独立执行:WorkManager的任务可以在应用退出后继续执行,适用于需要延迟执行或应用退出后仍需运行的任务。
- 灵活的触发器:可以根据需要设置不同的触发器,如定时任务、网络状态变化等。
- 自动管理:WorkManager会自动管理任务的执行和重试,减少了开发者的工作量。
- 兼容性:WorkManager会根据设备的API情况自动选择合适的实现方式,
2.简单任务:
/**
* @auth: njb
* @date: 2024/11/26 23:14
* @desc: 简单任务
*/
class MainWorker(context: Context, workerParams: WorkerParameters): Worker(context, workerParams) {
override fun doWork(): Result {
Log.e(Constants.TAG,"简单任务 执行完毕"+Result.success())
return Result.success()
}
}
3.周期性任务:
/**
* @auth: njb
* @date: 2024/11/26 23:34
* @desc: 周期性任务
*/
class PeriodicWork(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
Log.e(Constants.TAG,"周期性任务 执行完毕")
return Result.success()
}
}
4.传递数据:
package com.cloud.workmanagerdemo
import android.content.Context
import android.util.Log
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
/**
* @auth: njb
* @date: 2024/11/26 23:38
* @desc: 传达数据
*/
class TransferDataWork(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
val activityData = inputData.getString("data")
Log.e(Constants.TAG,"传递数据任务 $activityData ")
val data = Data.Builder()
.putString("data", "TransferDataWork的数据").build()
return Result.success(data)
}
}
5.任务链:
package com.cloud.workmanagerdemo
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
/**
* @auth: njb
* @date: 2024/11/26 23:38
* @desc: 任务链WorkManager
*/
class DisPatchWork(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
val activityData = inputData.getString("data")
Log.e(Constants.TAG, "任务链$activityData")
return Result.success()
}
}
6.主界面代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_main"
android:layout_width="200dp"
android:layout_height="40dp"
android:text="简单任务"
android:textColor="@color/white"
android:textSize="20sp"
android:onClick="mainWork"
android:gravity="center"
android:background="@color/design_default_color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"/>
<TextView
android:id="@+id/tv_data"
android:layout_width="200dp"
android:layout_height="40dp"
android:text="传递数据"
android:onClick="transferDataWork"
android:textColor="@color/white"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="20dp"
android:background="@color/design_default_color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_main" />
<TextView
android:id="@+id/tv_more"
android:layout_width="200dp"
android:layout_height="40dp"
android:text="任务链"
android:onClick="moreWork"
android:textColor="@color/white"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="20dp"
android:background="@color/design_default_color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_data" />
<TextView
android:id="@+id/tv_poll"
android:layout_width="200dp"
android:layout_height="40dp"
android:text="周期性任务"
android:onClick="periodicTask"
android:textColor="@color/white"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="20dp"
android:background="@color/design_default_color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_more"/>
</androidx.constraintlayout.widget.ConstraintLayout>
7.测试代码:
package com.cloud.workmanagerdemo
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.work.Data
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun mainWork(view: View?) {
/* val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val dateFormat = SimpleDateFormat("hh:mm:ss", Locale.getDefault())
val data = Data.Builder()
.putString("date", dateFormat.format(Date()))
.build()
val oneTimeWorkRequest = OneTimeWorkRequest
.Builder(MainWorker::class.java)
.setConstraints(constraints)
.setInputData(data)
.build()
WorkManager.getInstance(this@MainActivity).enqueue(oneTimeWorkRequest)
WorkManager.getInstance(this)
.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
.observe(this) { workInfo ->
workInfo?.let {
if(it.state.isFinished){
val outputData = workInfo.outputData
Log.e("传递数据任务", outputData.getString("data")!!)
}
}
}*/
val oneTimeWorkRequest: OneTimeWorkRequest =
OneTimeWorkRequest.Builder(MainWorker::class.java)
.setInitialDelay(2, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(this).enqueue(oneTimeWorkRequest)
}
fun transferDataWork(view: View?) {
val data = Data.Builder()
.putString("data", "Activity的数据").build()
val oneTimeWorkRequest: OneTimeWorkRequest = OneTimeWorkRequest.Builder(TransferDataWork::class.java)
.setInputData(data)
.build()
WorkManager.getInstance(this).enqueue(oneTimeWorkRequest)
//监听Worker回传的数据
WorkManager.getInstance(this)
.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
.observe(this) { value ->
if (value.state.isFinished) {
val outputData = value.outputData
Log.e("传递数据任务", outputData.getString("data")!!)
}
}
}
/**
* 任务链
* @param view
*/
fun moreWork(view: View?) {
val workerRequests: ArrayList<OneTimeWorkRequest> = ArrayList()
//任务1
val oneTimeWorkRequest1: OneTimeWorkRequest =
OneTimeWorkRequest.Builder(DisPatchWork::class.java)
.setInputData(Data.Builder().putString("data", "任务1").build())
.build()
//任务2
val oneTimeWorkRequest2: OneTimeWorkRequest =
OneTimeWorkRequest.Builder(DisPatchWork::class.java)
.setInputData(Data.Builder().putString("data", "任务2").build())
.build()
workerRequests.add(oneTimeWorkRequest1)
workerRequests.add(oneTimeWorkRequest2)
//任务3
val oneTimeWorkRequest3: OneTimeWorkRequest =
OneTimeWorkRequest.Builder(DisPatchWork::class.java)
.setInputData(Data.Builder().putString("data", "任务3").build())
.build()
WorkManager.getInstance(this)
.beginWith(workerRequests) //先执行的任务
.then(oneTimeWorkRequest3) //后执行的任务
.enqueue()
}
/**
* 周期性任务
* @param view
*/
fun periodicTask(view: View?) {
val periodicWorkRequest: PeriodicWorkRequest =
PeriodicWorkRequest.Builder(PeriodicWork::class.java, 15, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(this)
.enqueue(periodicWorkRequest)
}
}
8.日志打印:
9.实现效果如下:
10.使用场景:
- Service适用场景:适用于需要在应用内部持续运行的后台任务,如音乐播放、数据上传等。由于Service依赖于主线程,不适合进行耗时的操作。
- WorkManager适用场景:适用于需要延迟执行或应用退出后仍需运行的任务,如定时任务、数据同步等。WorkManager可以自动管理任务的执行和重试,减少了开发者的负担。
11.总结:
Service和WorkManager各有优缺点,选择使用哪一个取决于具体的需求场景。如果需要依赖应用内部运行的后台任务,且任务不涉及耗时操作,可以选择Service;如果需要延迟执行或应用退出后仍需运行的任务,且希望减少开发工作量,可以选择WorkManager。
12.后台任务选择:
场景 | 推荐 |
---|---|
需系统触发,不必完成 | ThreadPool + Broadcast |
需系统触发,必须完成,可推迟 | WorkManager |
需系统触发,必须完成,立即 | ForegroundService + Broadcast |
不需系统触发,不必完成 | ThreadPool |
不需系统触发,必须完成,可推迟 | WorkManager |
不需系统触发,必须完成,立即 | ForegroundService |
13.项目demo代码:
https://gitee.com/jackning_admin/work-manager-demo
原文地址:https://blog.csdn.net/u012556114/article/details/144334126
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!