IT评测·应用市场-qidao123.com
标题:
Android中WorkManager的简单使用
[打印本页]
作者:
南七星之家
时间:
2025-3-13 08:14
标题:
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
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4