Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday 20 October 2018

WorkManager jetpack in android

Hello, guys today I goes to write about android new library Jetpack component WorkManager.

 What is WorkManager?

 Workmanager is part of Android Jetpack library and an Architecture Component for background work that needs a combination of opportunity and guaranteed execution. WorkManager will take care of the care of the logic to start your work under a variety of situations, even if you navigate away from your app.

WorkManager is a flexible library that has many additional features ...

 1: Support for both asynchronous one-off and periodic tasks.
 2: Support for constraints such as network condition, storage space, and charging status
 3: Chaining of complex work requests, including running work in parallel.
 4: Output from one work request used as input for the next.
 5: Handles API level compatibility back to API level 14.
 6: Work with or without google play services
 7: Follow system health best practice.
 8: LiveData support to easily display work request state in UI.


WorkManager Components

WorkManager: Receives the work with specific arguments and enqueues that work.

Worker: Implements doWork() which executes the functionality on the background thread.

WorkRequest: Represent an individual task. It will tell you which Worker is enqueued as well as what contents it needs to meet in order for it to run. WorkRequest is an abstract class that you will be using with OneTimeWorkRequest or PerodicWorkRequest.

WorkStatus: Provide data for each WorkRequest Object.


Let's start

MainActivity.kt


class MainActivity : AppCompatActivity(),View.OnClickListener {


    private var TAG: String = MainActivity::class.java.simpleName
    private lateinit var workManager: WorkManager
    private lateinit var timeWorkRequest: OneTimeWorkRequest
    private lateinit var periodicWorkRequest: PeriodicWorkRequest

    private  var PERIODIC_REQUEST_TAG:String="periodic_request"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        workManager = WorkManager.getInstance()!!
        btnstart.setOnClickListener(this)
        btnstop.setOnClickListener(this)


    }

    private fun setupOneTimeWorker() {
        timeWorkRequest = OneTimeWorkRequest.Builder(MyWorker::class.java)?.build()
        workManager.enqueue(timeWorkRequest)
    }

    private fun setupPeriodicWorker() {

        val works = WorkManager.getInstance().getStatusesByTag(PERIODIC_REQUEST_TAG)

        if (works.value != null && works.value?.isNotEmpty()!!) {
            return        }

        val work = PeriodicWorkRequest.Builder(MyWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MINUTES, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MINUTES)
        periodicWorkRequest = work.build()

         workManager.enqueue(periodicWorkRequest)

    }

    private fun requestPerodicWorkerSecondMethod(){
        val statusesByTag = workManager.getStatusesByTag(PERIODIC_REQUEST_TAG)
        if (statusesByTag == null || statusesByTag.value?.size == 0) {

        } else {
            for (i in 0 until statusesByTag.value?.size!!) {
                Log.e("TAG", " perodic request id " + statusesByTag.value?.get(i)?.id + " Status " + statusesByTag.value?.get(i)?.state)
            }
        }
    }


    override fun onClick(view: View?) {
        if (view == btnstart) {
            setupOneTimeWorker()
        } else if (view == btnstop) {
            setupPeriodicWorker()
            // or           // requestPerodicWorkerSecondMethod()        }

    }
}

MyWorker.kt


class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    private val TAG: String = MyWorker::class.java.simpleName
    override fun doWork(): Result {

        sendNotification("Title", "Details")
        return Result.SUCCESS
    }


    fun sendNotification(title: String, message: String) {
        val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //If on Oreo then notification required a notification channel.        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(applicationContext, "default")
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)

        notificationManager.notify(1, notification.build())
    }

}


Thank you
Full Source code WorkManager-jetpack


No comments:

Post a Comment