Serviceを試す
Service | Android Developers
Serviceの基本的な動きを確認してみます。
まずログを吐くだけのサービスを用意します。プロセス名をsampleProcessにします。ここで設定したプロセス名はDeviceビューで確認できます。
2011/1/22 追記
プロセス名を設定しない場合は同じプロセスで実行されるようです。
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
Service | Android Developers
マニフェストファイル
<service android:name="SampleService" android:process=":sampleProcess"></service>
SampleService.java
public class SampleService extends Service { @Override public void onCreate() { super.onCreate(); Log.v("EXAMPLE", "service onCreate"); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.v("EXAMPLE", "service onStart"); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); Log.v("EXAMPLE", "service onDestroy"); } }
SampleServiceActivity
つづいて、ボタンからServiceをstart/stopするActivityを用意します。
public class SampleServiceActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button01 = (Button) findViewById(R.id.Button01); button01.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(SampleServiceActivity.this, SampleService.class); startService(intent); } }); Button button02 = (Button) findViewById(R.id.Button02); button02.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(SampleServiceActivity.this, SampleService.class); stopService(intent); } }); Button button03 = (Button) findViewById(R.id.Button03); button03.setOnClickListener(new OnClickListener() { public void onClick(View v) { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE); Log.v("EXAMPLE", "-----"); for (RunningServiceInfo runningServiceInfo : runningServices) { Log.v("EXAMPLE", runningServiceInfo.service.getClassName()); } } }); } }
これをエミュレータで動かしてみると、startとstopによりrunningServicesの中身が切り替わることが確認できます。
DDMSのDevicesビューでプロセスの起動が確認できますが、stopしてもプロセスは消えません。そういうものなんでしょうか。