样本意向服务
这是一个假装在后台加载图像的 IntentService
的例子。实现 IntentService
所需要做的就是提供一个调用 super(String)
构造函数的构造函数,并且需要实现 onHandleIntent(Intent)
方法。
public class ImageLoaderIntentService extends IntentService {
public static final String IMAGE_URL = "url";
/**
* Define a constructor and call the super(String) constructor, in order to name the worker
* thread - this is important if you want to debug and know the name of the thread upon
* which this Service is operating its jobs.
*/
public ImageLoaderIntentService() {
super("Example");
}
@Override
protected void onHandleIntent(Intent intent) {
// This is where you do all your logic - this code is executed on a background thread
String imageUrl = intent.getStringExtra(IMAGE_URL);
if (!TextUtils.isEmpty(imageUrl)) {
Drawable image = HttpUtils.loadImage(imageUrl); // HttpUtils is made-up for the example
}
// Send your drawable back to the UI now, so that you can use it - there are many ways
// to achieve this, but they are out of reach for this example
}
}
要启动 IntentService
,你需要发送一个 Intent
。例如,你可以从 Activity
这样做。当然,你不仅限于此。这是一个如何从 Activity
类召唤你的新 Service
的例子。
Intent serviceIntent = new Intent(this, ImageLoaderIntentService.class); // you can use 'this' as the first parameter if your class is a Context (i.e. an Activity, another Service, etc.), otherwise, supply the context differently
serviceIntent.putExtra(IMAGE_URL, "http://www.example-site.org/some/path/to/an/image");
startService(serviceIntent); // if you are not using 'this' in the first line, you also have to put the call to the Context object before startService(Intent) here
IntentService
按顺序处理其 Intent
s 中的数据,这样你就可以发送多个 Intent
而无需担心它们是否会相互碰撞。一次只处理一个 Intent
,其余的进入队列。当所有作业完成后,IntentService
将自动关闭。