//work version : 1.0.0-alpha10
class TestWork(context: Context,parameters: WorkerParameters) : Worker(context,parameters) {
override fun doWork(): Result {
Observable.timer(2L,TimeUnit.MINUTES,Schedulers.io())
.subscribe({
append(applicationContext,"Success")
},{ e->
append(applicationContext,"Error : ${e.message}")
})
return Result.SUCCESS
}
companion object {
fun append(context: Context,text:String){
val time = SimpleDateFormat("MM/dd hh:mm:ss", Locale.US).format(Date())
val buffer = StringBuilder(readLine(context))
buffer.appendln("$time $text")
context
.getSharedPreferences("Update",Context.MODE_PRIVATE)
.edit()
.putString("status",buffer.toString())
.apply()
}
fun readLine(context: Context):String{
return context
.getSharedPreferences("Update",Context.MODE_PRIVATE)
.getString("status","") ?: ""
}
}
}
上面的代码只是在两分钟后告诉我工作的结果。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startWork()
}
private fun startWork() {
val work = PeriodicWorkRequest.Builder(
TestWork::class.java,
20, TimeUnit.MINUTES
)
.setConstraints(createConstraint())
.build()
WorkManager.getInstance().enqueueUniquePeriodicWork(
"Test-Update",
ExistingPeriodicWorkPolicy.KEEP,
work
)
}
private fun createConstraint(): Constraints {
val builder = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
builder.setRequiresDeviceIdle(true)
}
builder.setRequiresStorageNotLow(true)
return builder.build()
}
}
启动MainActivity后,我正在上述代码中向WorkManager注册TestWork。
最后,我添加了代码,以在按下按钮时将保存在“首选项”中的TestWork的结果日志输出到文本视图。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startWork()
button.setOnClickListener {
status.text = TestWork.readLine(this)
}
}
我已经在相同的Lolipop(API 22)和Oreo(API 26)AVD上运行了这段代码,Lolipop已经输出了预期的结果,但是Oreo在任何时间长度内都没有输出任何输出。
我是否需要使用其他代码才能在Oreo中直接使用WorkManager?我已经使用过JobService,但是它也没有显示预期的结果。