How to update Android UI from a WorkManager

In this android programming source code example, we are going to update Android UI from a WorkManager.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to update Android UI from a WorkManager.

activity_main.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"    tools:context=".WorkManagerAndJobSchedule.WorkManagerAndJobScheduleActivity6">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp">

        <TextView
            android:id="@+id/tvdata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Empty Data..."
            android:textColor="#000000"
            android:textSize="19sp"/>

        <Button
            android:id="@+id/schedule"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:text="Schedule Work"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="19sp"
            android:layout_marginTop="10dp"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class WorkManagerAndJobScheduleActivity6 extends AppCompatActivity{

    private TextView tvdata;
    private Button schedule;
    private OneTimeWorkRequest oneTimeWorkRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_and_job_schedule6);
        tvdata = (TextView) findViewById(R.id.tvdata);
        schedule = (Button) findViewById(R.id.schedule);
        oneTimeWorkRequest = new OneTimeWorkRequest.Builder(WorkManager6.class).build();
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        if(workInfo != null &&  workInfo.getState().isFinished()){
                            tvdata.setText(workInfo.getOutputData().getString("data"));
                        }
                    }
                });
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWork();
            }
        });
    }
    private void startWork(){
        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
    }
}

WorkManager6.java

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class WorkManager6 extends Worker {
    private Data data;
    public WorkManager6(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        try {
            Thread.sleep(5000);
            data = new Data.Builder()
                    .putString("data", "Hello world, work completed on time")
                    .build();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Result.success(data);
    }
}

app/build.gradle

implementation ‘androidx.work:work-runtime:2.1.0-beta02’

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment