Best Practise JobIntentService Android Example

Published by inkskull on

Best Practise JobIntentService Android Example

One of Android’s greatest strengths is its ability to use system resources in the background regardless app execution.  sometimes it became the behavior to use system resources excessively. This tutorial shows Best Practise JobIntentService Android Example for doing background operation using  JobIntentService.

Checkout Background Execution Limits in Android O

Helper for processing work that has been enqueued for a job/service. When running on Android O or later, the work will be dispatched as a job via JobScheduler.enqueue. When running on older versions of the platform, it will use Context.startService.

 

1)Create a Worker.java extends JobIntentService

 

public class Worker extends JobIntentService {
    private static final String TAG = "Worker";
    public static final String RECEIVER = "receiver";
    public static final int SHOW_RESULT = 123;
    /**
     * Result receiver object to send results
     */
    private ResultReceiver mResultReceiver;
    /**
     * Unique job ID for this service.
     */
    static final int DOWNLOAD_JOB_ID = 1000;
    /**
     * Actions download
     */
    private static final String ACTION_DOWNLOAD = "action.DOWNLOAD_DATA";

    /**
     * Convenience method for enqueuing work in to this service.
     */
    public static void enqueueWork(Context context, WorkerResultReceiver workerResultReceiver) {
        Intent intent = new Intent(context, Worker.class);
        intent.putExtra(RECEIVER, workerResultReceiver);
        intent.setAction(ACTION_DOWNLOAD);
        enqueueWork(context, Worker.class, DOWNLOAD_JOB_ID, intent);
    }

    @SuppressLint("DefaultLocale")
    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Log.d(TAG, "onHandleWork() called with: intent = [" + intent + "]");
        if (intent.getAction() != null) {
            switch (intent.getAction()) {
                case ACTION_DOWNLOAD:
                    mResultReceiver = intent.getParcelableExtra(RECEIVER);
                   for(int i=0;i<10;i++){
                       try {
                           Thread.sleep(1000);
                           Bundle bundle = new Bundle();
                           bundle.putString("data",String.format("Showing From JobIntent Service %d", i));
                           mResultReceiver.send(SHOW_RESULT, bundle);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                    break;
            }
        }
    }
}

 

2)Add WAKELOCK Permission to Manifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />

3) Add JobIntentService class to Manifest.xml

<service android:name=".Worker" />

4)Create a WorkerResultReceiver.java to communicate with Activity from JobIntentService

public class WorkerResultReceiver extends android.support.v4.os.ResultReceiver {
    private static final String TAG = "WorkerResultReceiver";
    private Receiver mReceiver;

    /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler the handler object
     */
    public WorkerResultReceiver(Handler handler) {
        super(handler);
    }

    public void setReceiver(Receiver receiver) {
        mReceiver = receiver;
    }


    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (mReceiver != null) {
            mReceiver.onReceiveResult(resultCode, resultData);
        }
    }

    public interface Receiver {
        void onReceiveResult(int resultCode, Bundle resultData);
    }
}

5)Create MainActivity.java to enqueue work to JobIntentService, Initialize the WorkerResultReceiver, Show data from the Service

public class MainActivity extends AppCompatActivity implements WorkerResultReceiver.Receiver {
    WorkerResultReceiver mWorkerResultReceiver;
    TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWorkerResultReceiver = new WorkerResultReceiver(new Handler());
        mWorkerResultReceiver.setReceiver(this);
        mTextView = findViewById(R.id.tv_data);
        showDataFromBackground(MainActivity.this, mWorkerResultReceiver);
    }

    private void showDataFromBackground(MainActivity mainActivity, WorkerResultReceiver mWorkerResultReceiver) {
        Worker.enqueueWork(mainActivity, mWorkerResultReceiver);
    }

    public void showData(String data) {
        mTextView.setText(String.format("%s\n%s", mTextView.getText(), data));
    }

    @Override
    public void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
            case SHOW_RESULT:
                if (resultData != null) {
                    showData(resultData.getString("data"));
                }
                break;
        }
    }
}

6)Create MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.cretlabs.jobintentservice.MainActivity">

    <TextView
        android:id="@+id/tv_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 

Check out The Full Source in Github

Thank you Happy Coding 😀

 

Categories: Android

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com