Skip to content

Commit

Permalink
constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
azzumw committed Mar 3, 2022
1 parent bdc13f9 commit 37f893f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.example.background

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
Expand All @@ -42,6 +43,19 @@ class BlurActivity : AppCompatActivity() {
viewModel.outputWorkInfos.observe(this, workInfosObserver())

binding.goButton.setOnClickListener { viewModel.applyBlur(blurLevel) }

// Setup view output image file button
binding.seeFileButton.setOnClickListener {
viewModel.outputUri?.let { currentUri ->
val actionView = Intent(Intent.ACTION_VIEW, currentUri)
actionView.resolveActivity(packageManager)?.run {
startActivity(actionView)
}
}
}

// Hookup the Cancel button
binding.cancelButton.setOnClickListener { viewModel.cancelWork() }
}

/**
Expand Down Expand Up @@ -95,7 +109,17 @@ class BlurActivity : AppCompatActivity() {

if (workInfo.state.isFinished) {
showWorkFinished()
} else {
// Normally this processing, which is not directly related to drawing views on
// screen would be in the ViewModel. For simplicity we are keeping it here.
val outputImageUri = workInfo.outputData.getString(KEY_IMAGE_URI)

// If there is an output file show "See File" button
if (!outputImageUri.isNullOrEmpty()) {
viewModel.setOutputUri(outputImageUri)
binding.seeFileButton.visibility = View.VISIBLE
}
}
else {
showWorkInProgress()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ class BlurViewModel(application: Application) : ViewModel() {
* @param blurLevel The amount to blur the image
*/
internal fun applyBlur(blurLevel: Int) {

// Create charging constraint
val constraints = Constraints.Builder()
.setRequiresCharging(true)
.build()
// Add WorkRequest to Cleanup temporary images
var continuation = workManager
.beginUniqueWork(
Expand All @@ -73,6 +78,7 @@ class BlurViewModel(application: Application) : ViewModel() {

// Add WorkRequest to save the image to the filesystem
val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>()
.setConstraints(constraints)
.addTag(TAG_OUTPUT)
.build()

Expand Down Expand Up @@ -119,6 +125,10 @@ class BlurViewModel(application: Application) : ViewModel() {
outputUri = uriOrNull(outputImageUri)
}

internal fun cancelWork() {
workManager.cancelUniqueWork(IMAGE_MANIPULATION_WORK_NAME)
}

class BlurViewModelFactory(private val application: Application) : ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
Expand Down

0 comments on commit 37f893f

Please sign in to comment.