Background processing with IntentService class
This article explain the usage of IntentService class in android SDK to perform background processing to offload tasks from an application’s main thread (Your activity).
when IntentService jobs done, the results are sent back to the activity.
Good example whould be an application that uses background processing for REST calls; to download some data from the internet, parse it, and send it back to the application.
There are several ways to do background (asynchronous) processing tasks:
- AsyncTask
- Service(orIntentService)
- Implement your own Threading mechanism
while the 3rd options is too compilcated for this purpose you should consider one of the others generaly.
ASyncTaskenables proper and easy use of the UI thread.
AServiceis an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentServiceis a base class for Services that handle asynchronous requests (expressed as Intents) on demand.
With AsyncTask if the user goes to another Activity you can’t transfer that object to the other Activity so it dies.
You can communicate between Service and Activity, but it’s tricky to do it right using Binders.
Contents
- 1IntentService
-
- 1.0.1Base IntentService
-
- 2IntentService Example
-
- 2.0.1BgProcessingActivity.java
- 2.0.2BgProcessingIntentService.java
- 2.0.3BgProcessingResultReceiver.java
- 2.0.4AndroidManifest.xml
-
IntentService
Class Overview:
- Since: API Level 3
- IntentService is a base class for
1
<a href="http://developer.android.com/reference/android/app/Service.html">Service</a> s that handle asynchronous requests
- Clients send requests through
1
<a href="http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)">startService(Intent)</a> calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
- All requests are handled on a single worker thread — they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.
You should read more on the Class overview atdeveloper.android.com.
Class Usage:
To use it, extend IntentService and implement
1 | <a href="http://developer.android.com/reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent(Intent)</a> |
. IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
Base IntentService
Before I will continue with a full example of using IntentService you can look at how should a base IntentService looks:
12345678910111213141516 | import android.app.IntentService;import android.content.Intent;public class Downloader extends IntentService { public Downloader(String name) { super(name); // TODO Auto-generated constructor stub } @Override protected void onHandleIntent(Intent arg0) { // TODO Auto-generated method stub }} |
- IntentServicehas a single constructor that takes a string argument
“name“.It’s only use is in naming the
worker thread for theIntentService. - onHandleIntent(): This method is invoked on the worker thread with a request to process.
- You should not overrideonStartCommandmethod for your IntentService.
IntentService Example
BgProcessingActivity.java
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 | package itekblog.examples;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.widget.Toast;public class BgProcessingActivity extends Activity implements BgProcessingResultReceiver.Receiver { public BgProcessingResultReceiver mReceiver; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Toast.makeText(this, "Starting background processing...", Toast.LENGTH_LONG).show(); // register a reciever for IntentService broadcasts mReceiver = new BgProcessingResultReceiver(new Handler()); mReceiver.setReceiver(this); // start IntentService final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, BgProcessingIntentService.class); // optional: send Extra to IntentService // intent.putExtra("name", "value"); intent.putExtra("receiver", mReceiver); intent.putExtra("command", "query"); startService(intent); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { switch (resultCode) { case BgProcessingIntentService.STATUS_RUNNING: //show progress Toast.makeText(this, "Running", Toast.LENGTH_LONG).show(); break; case BgProcessingIntentService.STATUS_FINISHED: // hide progress & analyze bundle Toast.makeText(this, "OK", Toast.LENGTH_LONG).show(); break; case BgProcessingIntentService.STATUS_ERROR: // handle the error; Toast.makeText(this, "Error", Toast.LENGTH_LONG).show(); break; } } @Override public void onPause() { super.onPause(); if (mReceiver!=null) mReceiver.setReceiver(null); // clear receiver to avoid leaks. }} |
BgProcessingIntentService.java
123456789101112131415161718192021222324252627282930313233343536373839404142 | package itekblog.examples;import android.app.IntentService;import android.content.Intent;import android.os.Bundle;import android.os.ResultReceiver;import android.util.Log;public class BgProcessingIntentService extends IntentService { public static final int STATUS_RUNNING = 0; public static final int STATUS_FINISHED = 1; public static final int STATUS_ERROR = 2; public BgProcessingIntentService() { super(BgProcessingIntentService.class.getName()); } @Override protected void onHandleIntent(Intent arg0) { Log.d(BgProcessingIntentService.class.getName(), "service started..."); // sendBroadcast(); final ResultReceiver receiver = arg0.getParcelableExtra("receiver"); String command = arg0.getStringExtra("command"); Bundle b = new Bundle(); if(command.equals("query")) { receiver.send(STATUS_RUNNING, Bundle.EMPTY); try { // get some data or something //b.putParcelableArrayList("results", results); receiver.send(STATUS_FINISHED, b); } catch(Exception e) { b.putString(Intent.EXTRA_TEXT, e.toString()); receiver.send(STATUS_ERROR, b); } } Log.d(BgProcessingIntentService.class.getName(), "service stopping..."); this.stopSelf(); }} |
BgProcessingResultReceiver.java
12345678910111213141516171819202122232425262728 | package itekblog.examples;import android.os.Bundle;import android.os.Handler;import android.os.ResultReceiver;public class BgProcessingResultReceiver extends ResultReceiver { private Receiver mReceiver; public BgProcessingResultReceiver(Handler handler) { super(handler); } public void setReceiver(Receiver receiver) { mReceiver = receiver; } public interface Receiver { public void onReceiveResult(int resultCode, Bundle resultData); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (mReceiver != null) { mReceiver.onReceiveResult(resultCode, resultData); } }} |
AndroidManifest.xml
1 | <!--?xml version="1.0" encoding="utf-8"?--> |
don’t forget to register both files in your AndroidManifest.xml:
this method should work perfectly and the REST call is running in a background process, updating the activity when done.
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer