樣本意向服務

這是一個假裝在後臺載入影象的 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 按順序處理其 Intents 中的資料,這樣你就可以傳送多個 Intent 而無需擔心它們是否會相互碰撞。一次只處理一個 Intent,其餘的進入佇列。當所有作業完成後,IntentService 將自動關閉。