libro
www.tuyano.com
Google androidプログラミング入門

サービスを作成する (2/5)

作成:2010-11-01 21:36
更新:2010-11-01 21:38

■サービスの設計とAndroidManifest.xmlの準備

では、実際に簡単なサンプルを作成しながら、サービスの利用について考えていきましょう。ここでは「MySample」というアプリから、「MySampleService」というサービスを起動し、そこから結果を受け取りながら処理を行う、というものを考えてみます。

サービスを利用するには、まず必要なのは「AndroidManifest.xml」にサービスの登録を行うことです。ここでは、MySampleServiceという名前のクラスとしてサービスを用意します。以下のリストに、記述例をあげてあります。よく見ると、<application>タグ内に、
<service
        android:enabled="true"
        android:name=".MySampleService" />
というタグが追加されていることがわかるでしょう。これが、アプリからサービスを利用できるようにするための記述です。

サービスは、あるアプリから実行する別スレッドのようなもの、ではありません。独立したプログラムとして実行されており、どこからでも利用することができるように設計されています。サービスを利用するためには、ただAndroidManifest.xmlに「このサービスを使います」ということを記述しておけばいいだけなのです。それが、この<service>タグです。android:enabledtrueに設定し、それからandroid:nameで実行するサービスのクラス名を指定してやります。


これで下準備はできました。ついでに、アプリ側のレイアウトファイル(main.xml)のほうも確認をしておきましょう。今回は、TextView01というIDのTextViewを1つだけ用意しておきました。サービスから結果を受け取り、このTextView01に表示させよう、というわけです。

※プログラムリストが表示されない場合

AddBlockなどの広告ブロックツールがONになっていると、プログラムリスト等が表示されない場合があります。これらのツールをOFFにしてみてください。

●プログラム・リスト●

※AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
		xmlns:android="http://schemas.android.com/apk/res/android"
		package="jp.tuyano.sample"
		android:versionCode="1"
		android:versionName="1.0">
	<application
			android:icon="@drawable/icon"
			android:label="@string/app_name">
		<activity
				android:name=".MySample"
				android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

		<service
				android:enabled="true"
				android:name=".MySampleService" />

	</application>
	<uses-sdk android:minSdkVersion="4" />
</manifest>


※main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	xmlns:app="http://schemas.android.com/apk/res/jp.tuyano.sample"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
<TextView
	android:id="@+id/TextView01"
	android:text="OK"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:textSize="20pt" />
</LinearLayout>
※関連コンテンツ

「Google androidプログラミング入門」に戻る