Service的声明周期方法比Activity要少一些,只有onCreate、onStart、onDestory。有两种方式启动Service
1、通过startService启动
此时,service启动的时候会经历onCreate-->onStart的过程,Service停止的时候直接进入销毁过程(onDestory)。而如果是调用者自己直接退出而没有调用stopService,Service会一直在后台运行。直到下次调用者再启动起来,并明确调用stopService.
2、通过bindService启动
提供bindService启动Service,其只会运行onCreate,这个时候调用者跟service绑定在一起,如果调用者退出了,Service就会调用onUnbind -->onDestoryed,所谓绑定在一起就共存亡了。
实例:音乐后台播放
TestService.java:service的调用者
package com.shutao.testservice;
public class TestService extends Activity {
private Button start, stop;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.start_music);
stop = (Button) findViewById(R.id.stop_music);
OnClickListener startOnclick = new OnClickListener() {
@Override
public void onClick(View v) {
TestService.this.startService(new Intent(
"com.shutao.testservice.START_MUSIC_SERVICE"));
}
};
OnClickListener stopOnclick = new OnClickListener() {
@Override
public void onClick(View v) {
TestService.this.stopService(new Intent(
"com.shutao.testservice.START_MUSIC_SERVICE"));
finish();
}
};
start.setOnClickListener(startOnclick);
stop.setOnClickListener(stopOnclick);
}
}
MusicService .java:继承Service
public class MusicService extends Service {
private MediaPlayer mp;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
mp.stop();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mp = MediaPlayer.create(this, R.raw.zhangyu_little_sun);
mp.start();
}
}
最后别忘了在AndroidManifext.xml文件中声明:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shutao.testservice"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestService"
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=".MusicService">
<intent-filter>
<action android:name="com.shutao.testservice.START_MUSIC_SERVICE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>