最終更新:
moonlight_aska 2013年08月04日(日) 17:59:17履歴
サービスを起動/停止する方法は,
インテントを利用する方法では, Context#startService/stopServiceメソッドを利用する.

- インテントを利用する.
- バインドを利用する.
インテントを利用する方法では, Context#startService/stopServiceメソッドを利用する.

- TestService.java
- Serviceクラスを継承した実装クラスを作成する.
- Service#onStartCommandメソッドに起動時の処理を実装する.
- Service#onDestoryメソッドに終了時の処理を実装する.
package com.moonlight_aska.android.service01;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class TestService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
// 開始時にコール
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "サービス起動", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
// 終了時にコール
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "サービス終了", Toast.LENGTH_LONG).show();
}
}
- AndroidManifest.xml
- マニフェストファイルにサービスの宣言を登録する.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moonlight_aska.android.service01"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.moonlight_aska.android.service01.ServiceActivity"
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:name=".TestService"></service>
</application>
</manifest>
- ServiceActivity.java
- サービスを指定して, インテントのインスタンスを取得する.
- startServiceメソッドで, サービスを起動する.
- stopServiceメソッドで, サービスを停止する.
package com.moonlight_aska.android.service01;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class Service01 extends Activity implements View.OnClickListener {
private Button btn = null;
private Intent intent = null;
private boolean mode = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
btn = (Button)findViewById(R.id.service_btn);
btn.setOnClickListener(this);
// サービスクラスを指定
intent = new Intent(this, TestService.class);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.service_btn) {
if (!mode) {
// サービスの起動
startService(intent);
btn.setText(R.string.stop_label);
mode = true;
}
else {
// サービスの停止
stopService(intent);
btn.setText(R.string.start_label);
mode = false;
}
}
}
}
コメントをかく