The IntentService
class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService
isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
This tutorial shows Best Practice IntentService Android Example
An IntentService
has a few limitations:
- It can't interact directly with your user interface. To put its results in the UI, you have to send them to an
Activity
. - Work requests run sequentially. If an operation is running in an
IntentService
, and you send it another request, the request waits until the first operation is finished. - An operation running on an
IntentService
can't be interrupted.
IntentService
is the preferred way to perform simple background operations.
1)Create a WorkerIntentService.java extending IntentService
package com.cretlabs.intentservice; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; /** * Created by Gokul on 2/25/2018. */ public class WorkerIntentService extends IntentService { private static final String TAG = "WorkerIntentService"; public static final String RECEIVER = "receiver"; public static final int SHOW_RESULT = 123; /** * Result receiver object to send results */ private android.support.v4.os.ResultReceiver mResultReceiver; /** * Actions download */ public static final String ACTION_DOWNLOAD = "action.DOWNLOAD_DATA"; /** * Creates an IntentService. Invoked by your subclass's constructor. * */ public WorkerIntentService() { super(TAG); } @Override protected void onHandleIntent(@Nullable 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 Intent Service %d", i)); mResultReceiver.send(SHOW_RESULT, bundle); } catch (InterruptedException e) { e.printStackTrace(); } } break; } } } }
2)Create a ResultReceiver.java to communicate to activity from background
public class ResultReceiver extends android.support.v4.os.ResultReceiver { private static final String TAG = "ResultReceiver"; 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 ResultReceiver(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); } }
3)Create MainActivity.java
public class MainActivity extends AppCompatActivity implements ResultReceiver.Receiver { ResultReceiver mResultReceiver; TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mResultReceiver = new ResultReceiver(new Handler()); mResultReceiver.setReceiver(this); mTextView = findViewById(R.id.tv_data); showDataFromBackground(MainActivity.this, mResultReceiver); } private void showDataFromBackground(Context context , ResultReceiver mResultReceiver) { Intent intent = new Intent( context, WorkerIntentService.class); intent.putExtra(RECEIVER, mResultReceiver); intent.setAction(ACTION_DOWNLOAD); startService(intent); } 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; } } }
5)Create main_activity.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.intentservice.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>
Article is originally published in http://thoughtnerds.com/best-practice-intentservice-android-example/