IntentService クラスは、簡単な構造でスクリプトを実行できます。
1 つのバックグラウンドスレッドで
実行されるようにしますこれにより、長時間実行オペレーションを処理できます。
ユーザーインターフェースの応答性に影響を与えませんまた、
IntentService は、ユーザー インターフェースのライフサイクル イベントのほとんどの影響を受けないため、
AsyncTask がシャットダウンされる状況でも実行を継続
IntentService にはいくつかの制限があります。
-
ユーザー インターフェースと直接インタラクションすることはできません。結果を UI に表示するには、
Activityに送信する必要があります。 -
作業リクエストは順次実行されます。オペレーションが
IntentServiceで別のリクエストを送信した場合、リクエストは 最初のオペレーションが終了します。 -
IntentServiceで実行されているオペレーションは中断できません。
ただし、ほとんどの場合、実行には IntentService を使用することをおすすめします。
バックグラウンド処理が簡単になります。
このガイドでは、次の方法について説明します。
IntentServiceの独自のサブクラスを作成します。- 必要なコールバック メソッド
onHandleIntent()を作成します。 IntentServiceを定義する 指定します。
受信インテントを処理する
アプリの IntentService コンポーネントを作成するには、
IntentService を拡張し、その中に
onHandleIntent() をオーバーライドします。次に例を示します。
Kotlin
class RSSPullService : IntentService(RSSPullService::class.simpleName) override fun onHandleIntent(workIntent: Intent) { // Gets data from the incoming Intent val dataString = workIntent.dataString ... // Do work here, based on the contents of dataString ... } }
Java
public class RSSPullService extends IntentService { @Override protected void onHandleIntent(Intent workIntent) { // Gets data from the incoming Intent String dataString = workIntent.getDataString(); ... // Do work here, based on the contents of dataString ... } }
通常の Service コンポーネントのその他のコールバック(
onStartCommand() は、サービスによって
IntentService。IntentService では、
オーバーライドできます
IntentService の作成の詳細については、
IntentService クラス。
マニフェスト内でインテント サービスを定義する
IntentService は、アプリ マニフェストにもエントリが必要です。
このエントリを
<service>
その子要素の
<application> 要素:
<application android:icon="@drawable/icon" android:label="@string/app_name"> ... <!-- Because android:exported is set to "false", the service is only available to this app. --> <service android:name=".RSSPullService" android:exported="false"/> ... </application>
属性 android:name は、インスタンスのクラス名を指定します。
IntentService。
なお、
<service>
要素に
インテント フィルタ。「
サービスに処理リクエストを送信する Activity は、
明示的な Intent であるため、フィルタは必要ありません。また、
つまり、同じアプリ内のコンポーネントか、他のアプリケーションの
サービスにアクセスできます。
基本的な IntentService クラスを作成したので、処理リクエストを送信できます。
Intent オブジェクトで追加します。これらのオブジェクトを作成する手順は、
IntentService に送信する方法については、
バックグラウンド サービスに処理リクエストを送信します。